How to authenticate an access token using OWIN OAuthBearerAuthentication? How to authenticate an access token using OWIN OAuthBearerAuthentication? asp.net asp.net

How to authenticate an access token using OWIN OAuthBearerAuthentication?


As you know, UseOAuthAuthorizationServer has the job of authenticating the user. Then, UseOAuthBearerAuthentication has the job of ensuring that only authenticated users can access your application. Often, these two jobs are assigned to different web application. It looks like your application is doing both.

There are certainly some cases were you need to override the default OAuthBearerAuthenticationProvider. Maybe you do, or maybe you don't In my case, ApplicationCookie didn't quite fit the scenario. So, I'm storing a 3rd party JWT token in a cookie, rather than the header, and using it to indicate that the user is authenticated to a web application. I also needed to redirect to my own login page, rather than provide a 401.

Here's an implementation that does both:

public class CustomOAuthBearerProvider : IOAuthBearerAuthenticationProvider{    public Task ApplyChallenge(OAuthChallengeContext context)    {        context.Response.Redirect("/Account/Login");        return Task.FromResult<object>(null);    }    public Task RequestToken(OAuthRequestTokenContext context)    {        string token = context.Request.Cookies[SessionKey];        if (!string.IsNullOrEmpty(token))        {            context.Token = token;        }        return Task.FromResult<object>(null);    }    public Task ValidateIdentity(OAuthValidateIdentityContext context)    {        return Task.FromResult<object>(null);    }}

I didn't need to do anything special in ValidateIdentity, but I needed to satisfy the interface.

To wire this up, tell your app to use JwtBearerAuthentication with your provider:

// controllers with an [Authorize] attribute will be validated with JWTapp.UseJwtBearerAuthentication(    new JwtBearerAuthenticationOptions    {        AllowedAudiences = audiences.ToArray(),        IssuerSecurityTokenProviders = providers.ToArray(),        Provider = new CookieOAuthBearerProvider()    });