.net-core - 授权有效,但角色在 JWT 的 dotnet 核心中不起作用
问题描述
我像下面这样使用 JWT,当只使用Authorize时它可以正常工作,但是当想要使用Role时它不起作用
启动:
public void ConfigureServices(IServiceCollection services)
{
//...
AddOAuthProviders(services);
//...
}
public IServiceCollection AddOAuthProviders(IServiceCollection services)
{
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
return Task.CompletedTask;
},
};
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Security.secretKey)),
ValidateIssuer = false,
ValidateAudience = false
};
});
return services;
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IUnitOfWork uow)
{
//....
app.UseAuthentication();
app.UseAuthorization();
//...
}
在身份验证方法中:
//...
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserId.ToString()),
new Claim(ClaimTypes.Role, userRoles),//Read,Write
};
//...
控制器:
[HttpPost]
[Authorize(Roles = "Write")]
public ActionResult Insert ...
解决方案
看起来您正在通过执行以下操作在单个声明中添加多个角色:
new Claim(ClaimTypes.Role, userRoles)
如果您有多个角色,则每个角色都需要单独声明。像这样:
new Claim(ClaimTypes.Role, "Read")
new Claim(ClaimTypes.Role, "Write")
如果您在逗号分隔的字符串中获取角色userRoles
,则可以使用一些 Linq 魔法来添加角色:
claims.AddRange(userRoles.Split(',').Select(r => new Claim(ClaimTypes.Role, r)));
推荐阅读
- android - 使用 Kotlin 和 Retrofit 的 Android 项目中未解决的参考 call.enqueue 错误
- cordova - 为 Ionic App 创建和使用自定义 Cordova IOS 插件
- python - werkzeug.exceptions.BadRequestKeyError 当点击按钮
- python-3.x - Openpyxl创建带有表格的excel文件导致需要恢复错误的文件
- php - sql eloquent 模型中的 where 和 orderby 原因
- swift - 如何快速将具有相同对象的数组转换为单个对象?
- html - ERROR 错误:找不到带有路径的控件:'stocks -> stockName'
- sql - 在 Big Query 中制作连接表数组的最佳方法是什么?
- c# - 使用 EF Core 配置 Serilog ASP.Net Core 3.2 以记录 SQL 语句
- javascript - 导入时更改角度库的主题