此问题的原因可能是身份验证方案未配置正确,因此需要在Startup.cs文件中配置身份验证方案。在ConfigureServices方法中添加以下代码:
services.AddAuthentication(options => {
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options => {
options.Authority = Configuration["Auth0:Authority"];
options.Audience = Configuration["Auth0:Audience"];
});
在Configure方法中调用Authentication和Authorization中间件:
app.UseAuthentication();
app.UseAuthorization();
接下来,需要在应用程序中使用[Authorize]属性保护受保护的API端点(如/consumers或/common):
[Authorize]
[HttpGet("{id:int}")]
public async Task GetConsumer(int id)
{
var consumer = await _consumerService.GetConsumerAsync(id);
if (consumer == null)
{
return NotFound();
}
return Ok(consumer);
}
最后,需要在应用程序中的csproj文件中添加以下设置:
MySecrets
dotnet run --launch-profile Development
Exe
这样就可以正确地配置授权,并且在请求/consumers或/common端点时,将在HTTP请求标头中包含适当的Bearer token,以便进行有效身份验证和授权。