我的 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 调用未经授权,然后您重定向它们,那么它对 API 调用没有意义,那么我如何让它们进入 401 登录页面的正确方法是什么?
请记住,在这个项目中,我同时拥有 Web API 和带有 [Authorize] 属性的 Action 方法,因此仅当它是 Action 方法时我才需要重定向。
您可以使用StatusCodePages 中间件 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling#configuring-status-code-pages。将以下内容添加到您的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。将操作重定向到登录页面没有帮助,因为应用程序不知道如何在没有用户参与的情况下在后台验证自身身份。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)