gpt4 book ai didi

asp.net-core - 在 Asp.Net Core 2 中使用 JwtBearer 身份验证时返回 401 而不是重定向到登录页面

转载 作者:行者123 更新时间:2023-12-02 04:31:09 24 4
gpt4 key购买 nike

在启动时我有

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});

以后

app.UseAuthentication();

两个问题

  1. 除了那些具有 [AllowAnonymous] 的 Controller /操作之外,我如何将授权设置为默认启用?
  2. 如何让代码返回 401 而不是重定向到登录页面?

关于这个有很多问题和答案,但它们似乎总是与具有许多身份验证方案的站点有关,例如 cookie 和 jwt。我有一个纯 jwt 身份验证的后端,只有 token 颁发者端点将具有匿名访问权限,其他所有内容都经过身份验证和授权。

最佳答案

我需要配置 StatusCodePages 中间件以避免重定向。

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseStatusCodePages();
...
}

关于asp.net-core - 在 Asp.Net Core 2 中使用 JwtBearer 身份验证时返回 401 而不是重定向到登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48708567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com