Authentication 使用JWT时如何返回特定的状态代码
我正在使用.NETCore 中间件似乎神奇地让我设置了身份验证,这是我的代码Authentication 使用JWT时如何返回特定的状态代码,authentication,asp.net-core-webapi,Authentication,Asp.net Core Webapi,我正在使用.NETCore 中间件似乎神奇地让我设置了身份验证,这是我的代码 services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.A
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddCookie(option =>
{
option.LoginPath = "/account/";
// option.LogoutPath = "/account/logout";
})
.AddJwtBearer(jwtBearerOptions =>
{
jwtBearerOptions.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"])),
ClockSkew = TimeSpan.Zero
};
}
);
我遇到的问题是,当用户调用端点且未通过身份验证时,浏览器会提示用户输入用户名和密码
从我所读到的,这是因为401的反应
我想将响应代码从401更改为400(或任意数字)
我不知道怎么做。在JwtBearerEvents-property中使用HttpResponse-method,在AddAuthentication
中看不到任何选项:
jwtBearerOptions.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
context.Response.OnStarting(() =>
{
context.Response.StatusCode = 400;
return Task.CompletedTask;
});
return Task.CompletedTask;
}
};