Asp.net

如何使用 OWIN OAuthBearerAuthentication 驗證訪問令牌?

  • August 11, 2021

我想要的是:

  1. 令牌生成器使用 OAuthAuthorizationServer,令牌消費者使用 OAuthBearerAuthentication(驗證訪問令牌)。
  2. 使用 OWIN 管道來管理所有的東西,token 的東西和 web api 的東西。

程式碼呢:

public void Configuration(IAppBuilder app)
{
   app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
   {
       AuthorizeEndpointPath = "/Authorize",
       AllowInsecureHttp = true,
       Provider = new OAuthAuthorizationServerProvider 
       {
           OnGrantCustomExtension = GrantCustomExtension,
           OnValidateClientRedirectUri = ValidateClientRedirectUri,
           OnValidateClientAuthentication = ValidateClientAuthentication,
       }
   });

   app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
   {
       Provider = new OAuthBearerAuthenticationProvider 
       { 
           //Handles applying the authentication challenge to the response message.
           ApplyChallenge=MyApplyChallenge,

           //Handles processing OAuth bearer token.
           RequestToken=MyRequestToken,

           //Handles validating the identity produced from an OAuth bearer token.
           ValidateIdentity = MyValidateIdentity,
       }
   });

   app.UseWebApi(new WebApplication3.Config.MyWebApiConfiguration());
}

問題是什麼:

  1. OAuthBearerAuthenticationProviderApplyChallengeRequestToken的3 個屬性ValidateIdentity。如何實現這3種方法?
  2. 在令牌認證過程中,我的想法是解密訪問令牌,從客戶端驗證令牌,如果令牌被驗證,則將令牌的身份放入HttpContext.Current.User.

OAuthBearerAuthenticationProvider職責是完成前面的步驟。我對嗎?

如您所知,UseOAuthAuthorizationServer它的工作是對使用者進行身份驗證。然後,UseOAuthBearerAuthentication確保只有經過身份驗證的使用者才能訪問您的應用程序。通常,這兩個作業被分配給不同的 Web 應用程序。看起來你的應用程序正在做這兩個。

在某些情況下您需要覆蓋預設值OAuthBearerAuthenticationProvider。也許你這樣做,或者你不這樣做在我的情況下,ApplicationCookie不太適合這個場景。因此,我將第 3 方 JWT 令牌儲存在 cookie 中,而不是標頭中,並使用它來指示使用者已通過 Web 應用程序的身份驗證。我還需要重定向到我自己的登錄頁面,而不是提供 401。

這是一個實現兩者兼而有之的實現:

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

我不需要在 ValidateIdentity 中做任何特別的事情,但我需要滿足介面。

要將其連接起來,請告訴您的應用程序將 JwtBearerAuthentication 與您的提供程序一起使用:

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

引用自:https://stackoverflow.com/questions/25097221