繁体   English   中英

如何在ASP.NET Identity中将用户限制为仅一个访问令牌

[英]How to limit user to only one access token in ASP.NET Identity

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

这是我的启动课程:

 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”方法:

 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令牌的主要限制之一是它的到期时间。 因此,如果您生成了长期有效的令牌,那么它在很长的时间内有效。 因此,处理此类问题的一些常见方法是:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM