OAuth2 WebApi 令牌过期

OAuth2 WebApi Token Expiration

我正在尝试动态设置令牌过期时间,但它似乎一直默认为 20 分钟。

这是我的 ConfigureAuth:

public void ConfigureAuth(IAppBuilder app)
{

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(""),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);

}

这是我的 GrantResourceOwnerCredentials 方法:

    public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        var hasValidLogin = (new login().authenticate(context.UserName, context.Password, "") == "valid");

        if (hasValidLogin == false)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return Task.FromResult<object>(null);
        }

        var oAuthIdentity = CreateIdentity(context);
        var oAuthProperties = CreateProperties(context);

        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, oAuthProperties);

        context.Validated(ticket);
        return Task.FromResult<object>(null);
    }

这是我的 SetProperties 方法,我可以在其中设置到期时间:

    public static AuthenticationProperties CreateProperties(OAuthGrantResourceOwnerCredentialsContext context)
    {

        IDictionary<string, string> data = new Dictionary<string, string>
        {
            { "client_id", context.ClientId }
        };

        var response = new AuthenticationProperties(data);
        response.ExpiresUtc = DateTime.Now.AddMonths(1);

        return response;
    }

即使在那之后,令牌也在返回:

{
  "access_token": ".....",
  "token_type": "bearer",
  "expires_in": 1199,
  "client_id": ".....",
  ".expires": "Fri, 13 Nov 2015 20:24:06 GMT",
  ".issued": "Fri, 13 Nov 2015 20:04:06 GMT"
}

知道为什么我无法在当前位置设置过期时间吗?该服务器将采用具有不同指定到期时间的各种不同客户端,因此我认为这是执行此操作的地方。我应该在其他地方做这件事吗?谢谢!

您看到的行为直接由 OAuth2 授权服务器 总是 GrantResourceOwnerCredentials 通知(其他 Grant* 通知也受到影响):https://github.com/jchannon/katanaproject/blob/master/src/Microsoft.Owin.Security.OAuth/OAuthAuthorizationServerHandler.cs#L386

解决方法是将到期日期设置为 AuthenticationTokenProvider.CreateAsync(您用于 OAuthAuthorizationServerOptions.AccessTokenProvider 的 class):

只需将 context.Ticket.Properties.ExpiresUtc 设置为您选择的到期日期,它就会按预期工作:

public class AccessTokenProvider : AuthenticationTokenProvider
{
    public override void Create(AuthenticationTokenCreateContext context)
    {
        context.Ticket.Properties.ExpiresUtc = // set the appropriate expiration date.

        context.SetToken(context.SerializeTicket());
    }
}

您还可以查看 AspNet.Security.OpenIdConnect.Server,它是 OWIN/Katana 提供的 OAuth2 授权服务器的一个分支,它本身支持从 GrantResourceOwnerCredentials 开始设置到期日期:https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/tree/dev

您可以在 TokenEndPoint 方法而不是 GrantResourceOwnerCredentials 方法中设置它。请看我对类似问题的回答 .

希望对您有所帮助。

我会把它扔在这里,截至目前,有更简单的方法不需要创建新的 class,它只是设置选项:

OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
    ...
    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
    ..
};

我们有类似的情况,不同的客户端有不同的令牌超时,所以我们希望能够相应地设置过期时间。在我们实现的 AuthenticationTokenProvider 中,我们设置了过期时间,但它在令牌被签名时被覆盖了。

我们最终满意的解决方案是覆盖 TokenEndpoint 方法。然后我们就可以实现客户端特定的到期时间:

    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        if (context.TokenIssued)
        {
            // client information
            var accessExpiration = DateTimeOffset.Now.AddSeconds(accessTokenTimeoutSeconds);
            context.Properties.ExpiresUtc = accessExpiration;
        }

        return Task.FromResult<object>(null);
    }

*已编辑以解决竞争条件。