首页 文章

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

提问于
浏览
2

我在我的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方法时重定向 .

2 回答

  • 7

    你可以使用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")
           }
        });
    

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

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

  • 0

    感谢您的建议...在谷歌度过了一段美好的时光后,我可以找到您的帖子,这对我有用 . 您提出了一个非常好的观点,因为它对app API调用没有意义 .

    但是,我有一种情况,从应用程序调用的动作具有特定的符号路径( /api/[Controller]/[Action] ),这使我可以区分我的控制器是否已被浏览器或应用程序调用 .

    app.UseStatusCodePages(async context =>
    {            
        var request = context.HttpContext.Request;
        var response = context.HttpContext.Response;
        var path = request.Path.Value ?? "";
    
        if (response.StatusCode == (int)HttpStatusCode.Unauthorized && path.StartsWith("/api", StringComparison.InvariantCultureIgnoreCase))
        {
            response.Redirect("~/Account/Login");
        }
    });
    

相关问题