OAuth2 WebApi令牌过期

时间:2015-11-13 20:41:17

标签: asp.net oauth oauth-2.0 asp.net-web-api owin

我正在尝试动态设置令牌过期时间,但看起来它只是默认为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"
}

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

4 个答案:

答案 0 :(得分:12)

我们有类似的情况,不同的客户端具有不同的令牌超时,因此我们希望能够相应地设置到期时间。在我们实现的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);
    }

*编辑以解决竞争条件。

答案 1 :(得分:10)

当您在GrantResourceOwnerCredentials通知中设置OAuth2授权服务器 总是放弃您自己的到期时,您所看到的行为是直接造成的。 1}}通知也会受到影响):https://github.com/jchannon/katanaproject/blob/master/src/Microsoft.Owin.Security.OAuth/OAuthAuthorizationServerHandler.cs#L386

解决方法是设置到期日期 Grant*(您用于AuthenticationTokenProvider.CreateAsync的课程):

只需将OAuthAuthorizationServerOptions.AccessTokenProvider设置为您选择的到期日期,它应该按照预期的方式运行:

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()); } } ,这是OWIN / Katana提供的OAuth2授权服务器的分支,本机支持从AspNet.Security.OpenIdConnect.Server设置到期日期:https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/tree/dev

答案 2 :(得分:2)

您可以使用TokenEndPoint方法而不是GrantResourceOwnerCredentials方法进行设置。请参阅我对类似问题的回答here

我希望它有所帮助。

答案 3 :(得分:2)

我会把它扔出去,截至目前,没有创建新类的方法更简单,它只是设置选项:

OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
    ...
    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
    ..
};
相关问题