本文介绍了如何在ASP.NET Identity中将用户限制为仅一个访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的webApi应用程序中使用基于令牌的身份验证.对于每次登录,OAuth都会为用户生成一个访问令牌.如果用户尝试多次登录.它可能拥有一些更有效的令牌.这个过程有限制吗?

I'm Using Token-Based Authentication in my webApi application. for each login OAuth generates an access token for user. if a user tries to do login more than once. it may own some more valid token. is there a limitation on this process.

这是我的启动课程:

 public void Configuration(IAppBuilder app)
 {
     HttpConfiguration config = new HttpConfiguration();

     ConfigureOAuth(app);

     WebApiConfig.Register(config);
     app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
     app.UseWebApi(config);
     //Rest of code is here;
 }

 public void ConfigureOAuth(IAppBuilder app)
 {
     OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
     {
         AllowInsecureHttp = true,
         TokenEndpointPath = new PathString("/token"),
         AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
         Provider = new SimpleAuthorizationServerProvider()
     };

     // Token Generation
     app.UseOAuthAuthorizationServer(OAuthServerOptions);
     app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
 }

这是"GrantResourceOwnerCredentials"方法:

and here is "GrantResourceOwnerCredentials" Method:

 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
 context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

 using (AuthRepository _repo = new AuthRepository())
 {
     IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

     if (user == null)
     {
         context.SetError("invalid_grant", "The user name or password is incorrect.");
         return;
     }
 }

 var identity = new ClaimsIdentity(context.Options.AuthenticationType);
 identity.AddClaim(new Claim("sub", context.UserName));
 identity.AddClaim(new Claim("role", "user"));

 context.Validated(identity);

 }

推荐答案

oauth令牌的主要限制之一是它的到期时间.因此,如果您生成了长期有效的令牌,那么该令牌将长期有效.因此,处理此类问题的一些常见方法是:

One of the main limitation of oauth token is it's expiry. So if you generate long living token then it is valid for long time. So some of common approach to handle such senerio is :

  • 发布带有其他刷新令牌的短期令牌

  • issue short living token with additional refresh token

将令牌存储在数据库中,并且每次生成新令牌时,都会使旧的一个令牌状态失效.然后,您可以编写自定义授权属性,以检查令牌是否已过期.

store token in database and every time when new token is generated then make old one token status to expire. Then you can write your custom authorize attribute to check whether token is expire or not.

这篇关于如何在ASP.NET Identity中将用户限制为仅一个访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 20:29