本文介绍了OAuth2 WebApi 令牌到期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to set a token expiration time dynamically, but it appears it just keeps defaulting to 20 minutes.

这是我的 ConfigureAuth:

Here is my 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 方法:

Here is my GrantResourceOwnerCredentials method:

    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 方法,我可以在其中设置到期时间:

And here is my SetProperties method where I can setting the expiration:

    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;
    }

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

Even after that, the token is returning:

{
  "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"
}

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

Any ideas why I cannot set the expiration where I currently am? This server will take a variety of different clients with different specified expiration times, therefore I figured this is the place to do this. Is there somewhere else that I should doing this at? Thanks!

推荐答案

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

The behavior you're seeing is directly caused by the fact the OAuth2 authorization server always discards your own expiration when you set it in the GrantResourceOwnerCredentials notification (the other Grant* notifications are also impacted): https://github.com/jchannon/katanaproject/blob/master/src/Microsoft.Owin.Security.OAuth/OAuthAuthorizationServerHandler.cs#L386

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

A work around is to set the expiration date inAuthenticationTokenProvider.CreateAsync (the class you use for OAuthAuthorizationServerOptions.AccessTokenProvider):

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

Simply set context.Ticket.Properties.ExpiresUtc with the expiration date of your choice, and it should work as intented:

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


You can also take a look at AspNet.Security.OpenIdConnect.Server, a fork of the OAuth2 authorization server offered by OWIN/Katana that natively supports setting the expiration date from GrantResourceOwnerCredentials: https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/tree/dev

这篇关于OAuth2 WebApi 令牌到期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 10:15