c# - 升级到 NET Core 3.1 后,Authorize 属性始终返回 401
问题描述
我的 NET Core 3.1 REST API 当前在标记有 [Authorize] 属性的调用上返回 401。没有授权属性的调用,或者允许匿名的调用,或者如果我从控制器中删除了授权属性,都是成功的。
我最近将 API 从 Core 2 更新到 core 3.1,这让我相信代码在 2 到 3.1 之间的预期不同。
通过查看 StackOverflow 和在线上的其他问题,大多数都指向启动时配置功能中的项目顺序,尽管我的看起来与 Microsoft 文档中的内容相匹配。我没有更改我的令牌生成代码,因为当我收到它们并在 JWT.io 中测试它们时,从 2 更新到 3.1 令牌看起来确实有效,但与以前一样,当通过 Postman 运行调用时,或从前端应用程序调用立即 401s在授权步骤。
下面是一些代码片段:
Startup.cs - 配置服务
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
// Get appsettings from config file
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
var appSettings = appSettingsSection.Get<AppSettings>();
services.AddDbContext<MuglensContext>(options => options.UseSqlServer(appSettings.DBConnection));
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.JWTKey))
};
});
// Underneath this is adding of scoped services
Startup.cs - 配置
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(builder => builder
.WithOrigins(Configuration["Origins"])
.AllowAnyHeader()
.AllowAnyMethod()
);
//AuthAppBuilderExtensions.UseAuthentication(app);
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
AuthService.cs - 生成令牌
private string GenerateToken(string email, string userID)
{
var claims = new[]
{
new Claim("email", email),
new Claim("userID", userID)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.JWTKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _settings.Origins,
audience: _settings.Origins,
claims: claims,
expires: DateTime.Now.AddMinutes(45),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
任何帮助将非常感激。
解决方案
您是否尝试过针对Authoize
属性中的 JWT 模式进行验证?
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]`
在命名空间中Microsoft.AspNetCore.Authentication.JwtBearer
。
并在您的服务中注册该架构,例如
services.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
...
推荐阅读
- python - python中的网络抓取:为每个网页复制HTML的特定部分
- php - PHP日期函数提取原始时间戳?
- javascript - Redux/React:更改 activePage 时无法读取未定义的属性“类型”
- java - Android Studio Socket.io 每隔几秒就会断开连接并重新连接
- python - 在 Python 中用另一个更大的张量替换一个张量的一部分
- python - 如何将 Python 中的顶部和底部 x 轴与 Matplotlib 匹配?
- javascript - TypeScript 中的“数字”和“数字”有什么区别?
- javascript - 将一个对象放在左侧,将第二个放在右侧
- python - 类型错误:使用 pandas DataFrame 执行 .loc 时,只能将整数标量数组转换为标量索引
- string - 使用带和不带 ret 的 shellcode 构建字符串