How to authenticate an access token using OWIN OAuthBearerAuthentication?

前端 未结 1 1262
花落未央
花落未央 2021-02-06 04:45

What I want:

  1. A token generator use OAuthAuthorizationServer and token consumer use OAuthBearerAuthentication (authenticate the access token).
相关标签:
1条回答
  • 2021-02-06 05:00

    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 JWT
    app.UseJwtBearerAuthentication(
        new JwtBearerAuthenticationOptions
        {
            AllowedAudiences = audiences.ToArray(),
            IssuerSecurityTokenProviders = providers.ToArray(),
            Provider = new CookieOAuthBearerProvider()
        }
    );
    
    0 讨论(0)
提交回复
热议问题