Mahmoud Moravej
Mahmoud Moravej

Reputation: 9034

How to invalidate bearer token at server

I save all of the generated bearer tokens into a database at sign-in time. Now I want to check if the request bearer does not exists in database, reject it. Where should I put it?

Note that I want this to happen in the Owin pipeline. (Not in the webapi pipeline. For example inside the [Authorize] attribute)

Upvotes: 4

Views: 3505

Answers (1)

Mahmoud Moravej
Mahmoud Moravej

Reputation: 9034

Inherit from OAuthBearerAuthenticationProvider like this :

public class ApplicationOAuthBearerAuthenticationProvider : OAuthBearerAuthenticationProvider
{    

    public override Task ValidateIdentity(OAuthValidateIdentityContext context)
    {            
        var result=  base.ValidateIdentity(context);

        if (context.IsValidated )
        {
            var ticket = context.Ticket;

            if (ticket != null && ticket.Identity.IsAuthenticated && ticket.Properties.ExpiresUtc > DateTime.UtcNow)
            {
                if (1==2)//TODO: put your server side condition here
                {
                    context.SetError("HaHa!");
                }
            }

        }

        return result;

    }

}

and use it in your startup.cs class like this :

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
        {
            Provider = new ApplicationOAuthBearerAuthenticationProvider(),             
        });  
    }
}

Upvotes: 3

Related Questions