Search code examples
authenticationoauth-2.0asp.net-web-api2asp.net-identity

How to sign authenticated user out in Oauth 2.0 token based?


I am using oauth 2.0 with Identity framework in a web api application.

In my web api I implemented authentication using Token-based authentication and refresh token. I need to sign the user out when his password changes(Here the security stamp will be changed).

I have this code:

app.UseCookieAuthentication(new CookieAuthenticationOptions {
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider {
    // Enables the application to validate the security stamp when the user logs in.
    // This is a security feature which is used when you change a password or add an external login to your account.  
    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
        validateInterval: TimeSpan.FromMinutes(30),
        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}});

But I think it's for cookie-based authentication Here is my code to configure token generation:

var oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/api/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = provider,
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };

I have implemented my provider to check user credentials and refresh token provider to achieve sliding access token expiration.

My first question is how to implement rejecting the access token/refresh token to sign the user out by checking securitystamp?.

My second question Should I do it inside my access token provider and/or refresh token provider(if there is any code snippt it would be better to understand)?


Solution

  • In token-based authentication there is no out-of-the-box solution for invalidating access token based on securityStamp changes . But I have found a good solution for this problem on this page:

    How to invalidate OAuth token when password is changed?

    But the above solution does not implement owin.So briefly the solution would be like the followings:

    Step1: When you grant resource owner credentials inside your provider(inside GrantResourceOwnerCredentials method) add claim named for example "securityStamp" and get its value(which is here Guid represents the securityStamp column for the authenticated user) from the database.

    Step2: Create an owinmiddlerware and inside it check the value of the securityStamp if it's changed(by comparing the value of securityStamp claim with the value stored inside the database) then log the user out to get new access token.