相关疑难解决方法(0)

如何使用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,
        ValidateLifetime = true
    };
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

asp.net-core

7
推荐指数
1
解决办法
3099
查看次数

标签 统计

asp.net-core ×1