oauth2刷新令牌,具有较长的到期时间

时间:2018-07-17 19:25:33

标签: asp.net .net rest oauth-2.0 asp.net-web-api2

我有一个oauth2 api,我的令牌在1天后过期,但我希望用户能够保持登录状态,在这种情况下,客户端要求刷新令牌在1年后过期。问题是,当我使刷新令牌在1天而不是1年后过期时。

这里有一些代码片段可以帮助您了解我的情况。

Startup.cs

// Enable authentication by token
        var options = new OAuthAuthorizationServerOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
            AuthenticationMode = AuthenticationMode.Active,
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/auth/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(10),
            Provider = container.Resolve<IOAuthAuthorizationServerProvider>(GetAuthorizationProviderName()),
            RefreshTokenProvider = container.Resolve<IAuthenticationTokenProvider>()
        };

RefreshTokenProvider.cs [IAuthenticationTokenProvider]

        public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        var clientId = context.Ticket.Properties.Dictionary["as:client_id"];

        if (clientId.IsEmpty()) return;

        var refreshToken = Guid.NewGuid().ToString("n");

            var application = _repository.GetAllApplicationsAsync().ByAppId(clientId);

            var token = new RefreshToken(
                plainTextToken: refreshToken,
                issuedUtc: DateTime.UtcNow,
                expiresUtc: DateTime.UtcNow.AddYears(1),
                serializedAuthTicket: context.SerializeTicket());

            await _repository.SaveAsync(token);

            context.Ticket.Properties.IssuedUtc = token.IssuedUtc;
            context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;

            context.SetToken(refreshToken);
        }
    }

public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
        var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
        context.OwinContext.Response.Headers.Set("Access-Control-Allow-Origin", allowedOrigin);

        var hashedTokenId = Crypto(context.Token);

            var token = await _repository.GetAllTokensAsync().ByTokenAsync(hashedTokenId);

            if (token != null)
            {
                context.DeserializeTicket(token.SerializedAuthTicket);

                await _repository.DeleteAsync(hashedTokenId);
            }
    }

OAuth2Provider.cs [IOAuthAuthorizationServerProvider]

public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
    {
        var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
        var currentClient = context.ClientId;

        if (originalClient != currentClient)
        {
            context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
            return;
        }

        var claimsIdentity = new ClaimsIdentity(context.Ticket.Identity);
        claimsIdentity.AddClaim(new Claim("newClaim", "refreshToken"));

        var updatedTicket = new AuthenticationTicket(claimsIdentity, context.Ticket.Properties);
        context.Validated(updatedTicket);
    }

这是令牌API的响应

{
"access_token": "qeZlgDHBkqx0m4TVPzhjr6ioOdATTW0KrweHKhawVLhXeBGGdFgB1B0GL9_[omitted]",
"token_type": "bearer",
"expires_in": 86399,
"refresh_token": "8925f5070f0249508761009378fde92a",
"username": "master",
"last_logon": "Tue, 17 Jul 2018 15:59:12 GMT",
"as:client_id": "abc123",
".issued": "Tue, 17 Jul 2018 19:19:44 GMT",
".expires": "Wed, 18 Jul 2018 19:19:44 GMT"

}

这是刷新令牌api的响应。

{
"access_token": "-AnSGFnLGKO1QnzkmP0QyHno5uR-[omitted]",
"token_type": "bearer",
"expires_in": 86399,
"refresh_token": "32b5050dc8ec488abaf1df6bb3c96ec0",
"username": "master",
"last_logon": "Tue, 17 Jul 2018 15:59:12 GMT",
"as:client_id": "abc123",
".issued": "Tue, 17 Jul 2018 19:23:24 GMT",
".expires": "Wed, 18 Jul 2018 19:23:24 GMT"

}

1 个答案:

答案 0 :(得分:0)

在讨论了问题之后,我确实相信,当您请求刷新令牌时,它的持续时间将与您之前获得的相同。出于测试目的,您可以将第一个调用更改为获取令牌1年,并查看其是否再刷新一年。

如果您想更改令牌到期的时间跨度,我相信您必须请求另一个具有新时间跨度的令牌,然后刷新该令牌。