问题描述: 在ASP.NET Core项目中,使用JWT进行身份验证时,当用户未授权时,返回状态码401并显示“未授权。策略验证”错误信息。
解决方法: 下面是一个包含代码示例的解决方案,来处理JWT身份验证时出现的未授权问题。
public void ConfigureServices(IServiceCollection services)
{
// 配置JWT身份验证
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:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 启用身份验证中间件
app.UseAuthentication();
// 其他中间件配置
// ...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
// ...
}
通过以上步骤,当用户未携带有效的JWT令牌时,将返回状态码401并显示“未授权。策略验证”错误信息。
希望以上解决方案能够帮助到你解决问题。
上一篇:ASP.Net Core JS在_Layout中可以运行,但在body页面中无法运行。
下一篇:ASP.NET Core JWT Bearer Authentication与外部Windows身份验证的可能性