如何使用ASP.NET Core中的JWT授权重定向到401上的登录页面

g_b*_*g_b 7 asp.net-core

我在我的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
    };
});
Run Code Online (Sandbox Code Playgroud)

我的HomeController有[Authorize]属性.因此,在访问Home/Index时,我收到了401响应,并且我看到了一个空白页面.我想重定向到我的帐户/登录页面,但我不知道该怎么做.

我读到这不应该自动重定向,因为如果它们没有被授权然后你重定向它们对API调用没有意义,那么我将如何将它们带到401的登录页面的正确方法是什么.

请记住,在这个项目中,我同时拥有带有[Authorize]属性的Web API和Action方法,所以我只需要在它是一个action方法时重定向.

Set*_*Set 12

您可以使用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")
       }
    });
Run Code Online (Sandbox Code Playgroud)

我读到这不应该自动重定向,因为它对API调用没有意义

这与API调用有关,它返回页面以外的数据.假设您的应用在后台调用API.将操作重定向到登录页面没有帮助,因为应用程序不知道如何在没有用户参与的情况下在后台验证自身.