如何在 ASP.NET Core 中使用 JWT 授权重定向到 401 上的登录页面 [英] How to redirect to log in page on 401 using JWT authorization in ASP.NET Core

查看:24
本文介绍了如何在 ASP.NET Core 中使用 JWT 授权重定向到 401 上的登录页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 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,验证生命周期 = 真};});

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

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

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

解决方案

您可以使用 StatusCodePages 中间件.在您的 Configure 方法中添加以下内容:

app.UseStatusCodePages(async context => {var request = context.HttpContext.Request;var response = context.HttpContext.Response;if (response.StatusCode == (int)HttpStatusCode.Unauthorized)//您也可以检查请求路径以仅针对特定方法执行此操作//&&request.Path.Value.StartsWith("/specificPath"){response.Redirect("/账户/登录")}});

<小时><块引用>

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

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

I have this JWT authorization configuration in my Startup.cs:

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

My HomeController has [Authorize] attribute. So upon access to Home/Index, I get a 401 response and I am presented with a blank page. I want to redirect to my Account/LogIn page but I am not sure how to do it.

I read that this shouldn't automatically redirect because it won't make sense to API calls if they are not authorized and then you redirect them, so what is the proper way on how I would get them to the login page on 401.

Please bear in mind that in this project, I have both Web API and Action methods with [Authorize] attributes so I need to redirect only when it is an action method.

解决方案

You may use StatusCodePages middleware. Add the following inot your Configure method:

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


I read that this shouldn't automatically redirect because it won't make sense to API calls

this relates to API calls, that returns data other than pages. Let's say your app do call to API in the background. Redirect action to login page doesn't help, as app doesn't know how to authenticate itself in background without user involving.

这篇关于如何在 ASP.NET Core 中使用 JWT 授权重定向到 401 上的登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆