加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-core – 如何使用ASP.NET Core中的JWT授权重定向到401上

发布时间:2020-12-16 00:00:40 所属栏目:asp.Net 来源:网络整理
导读:我在我的Startup.cs中有这个JWT授权配置: services.AddAuthentication(opts ={ opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultAuthentic
我在我的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调用没有意义,那么我将如何将它们带到401上的登录页面的正确方法是什么.

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

解决方法

您可以使用 StatusCodePages middleware.在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")
       }
    });

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读