简体   繁体   中英

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

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.

Here is my Startup class:

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

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

 }

I am afraid the token is valid until it expires and it will contain all the info related to the user.

So to do what you want you have to create your own layer to validate if the user has or not a token, like creating a mapping table and then a custom filter to reject the request if the user is not using the last token generated for him.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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