Asp.net-Core

如何在 ASP.NET Core 中使用 JWT 授權重定向到 401 上的登錄頁面

  • November 9, 2021

我的 Startup.cs 中有這個 JWT 授權配置:

services.AddAuthentication(opts =>
{
   opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
   opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
   opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(opts =>
{
   opts.RequireHttpsMetadata = false;
   opts.SaveToken = true;
   opts.TokenValidationParameters = new TokenValidationParameters()
   {
       IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("my_secret_key")),
       ValidIssuer = "iss",
       ValidAudience = "aud",
       ValidateIssuerSigningKey = true,
       ValidateLifetime = true
   };
});

我的 HomeController 有

$$ Authorize $$屬性。因此,在訪問 Home/Index 時,我會收到 401 響應,並且會看到一個空白頁面。我想重定向到我的帳戶/登錄頁面,但我不知道該怎麼做。 我讀到這不應該自動重定向,因為如果 API 呼叫未經授權然後你重定向它們,那麼它對 API 呼叫沒有意義,那麼如何讓它們進入 401 上的登錄頁面的正確方法是什麼。

請記住,在這個項目中,我有 Web API 和 Action 方法

$$ Authorize $$屬性,所以我只需要在它是一種操作方法時才需要重定向。

您可以使用StatusCodePages 中間件。在您的方法中添加以下內容Configure

app.UseStatusCodePages(async context => {
   var request = context.HttpContext.Request;
   var response = context.HttpContext.Response;

   if (response.StatusCode == (int)HttpStatusCode.Unauthorized)   
      // you may also check requests path to do this only for specific methods       
      // && request.Path.Value.StartsWith("/specificPath")

      {
          response.Redirect("/account/login")
      }
   });

我讀到這不應該自動重定向,因為它對 API 呼叫沒有意義

這與返回頁面以外的數據的 API 呼叫有關。假設您的應用在後台呼叫 API。將操作重定向到登錄頁面沒有幫助,因為應用程序不知道如何在沒有使用者參與的情況下在後台進行身份驗證。

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