在ASP.NET Core 3.1中,当使用Bearer令牌进行身份验证时,可以遇到401错误。以下是一个解决这个问题的代码示例:
public void ConfigureServices(IServiceCollection services)
{
// 添加身份验证服务
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// 配置令牌验证参数
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your-issuer",
ValidAudience = "your-audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"))
};
});
// 添加授权策略
services.AddAuthorization();
// 其他服务配置...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 其他中间件配置...
// 添加身份验证和授权中间件
app.UseAuthentication();
app.UseAuthorization();
// 其他中间件配置...
}
[Authorize]
属性来限制访问:[Authorize]
public class YourController : ControllerBase
{
// 操作方法...
}
这些代码示例中,配置的身份验证服务和授权策略将会使用Bearer令牌进行验证。如果请求未包含有效的Bearer令牌或令牌验证失败,将返回401错误。请确保替换示例代码中的实际值,如令牌验证参数中的签发者、受众、密钥等。