asp.net - 当用户未经身份验证时,ASP.NET Core 5 Web API 返回 404 代码而不是 401
问题描述
我有一个基于 ASP.NET 5 框架和 Swagger UI 编写的 Web API。
当用户向任何端点发出经过身份验证的请求时,我得到 404 “就像框架将用户重定向到不存在的页面一样!” 如果框架由于未经授权的请求而自动重定向请求,我想更改该行为以返回 401 json 响应。如果没有,如何将响应代码从 404 更改为 401 作为 JSON 响应?
这是 Startup 类的样子
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(swagger =>
{
swagger.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Student Athlete Wellness Tracker API",
Description = "API to provide data for the Student Athlete Wellness Trackers",
});
swagger.AddSecurityDefinition("basic", new OpenApiSecurityScheme()
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "basic",
In = ParameterLocation.Header,
Description = "Basic Authorization header using the Bearer scheme.",
});
swagger.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "basic"
}
},
Array.Empty<string>()
}
});
});
services.AddAuthentication("BasicAuthentication")
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/error");
app.UseHsts();
}
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Student Athlete Wellness Trackers - v1"));
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
解决方案
我遇到了同样的问题。
我添加了第二个选项行,这解决了问题。
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
可以阅读官方文档了解更多:<a href="https://docs.microsoft.com/en-us/aspnet/core/security/authentication/?view=aspnetcore-5.0" rel="nofollow noreferrer" >https://docs.microsoft.com/en-us/aspnet/core/security/authentication/?view=aspnetcore-5.0
示例:<a href="https://stackoverflow.com/questions/52038054/web-api-core-returns-404-when-adding-authorize-attribute">Web api core在添加Authorize属性时返回404
推荐阅读
- javascript - JavaScript - 减少数组
- javascript - 根据标签在页面上创建导航/指标
- c - IORING_ENTER_SQ_WAKEUP - 对“io_uring_enter”的未定义引用
- javascript - 未捕获的 ReferenceError:函数未在 HTMLDivElement.onclick 中定义
- r - Rmarkdown 文件不是编织的,它不允许执行 for 循环
- nlp - ValueError:使用 MFCC 提取特征时,无法使用“常量”或“空”以外的模式扩展空轴 0
- python - 使用 AWS Lambda 函数将 .txt 转换为 .csv
- azure - .NET Core 3.1 的应用程序洞察实时指标没有数据
- jquery - 第一次ajax成功后,jquery Ajax徽标删除不起作用Laravel 7 jquery
- linux - 我正在尝试将 I2C 与 beaglebone 一起使用,但我不能写入超过 1 个字节