.net-core - dotnet core IdentityServer 添加角色
问题描述
请提前接受我的道歉。这个话题遍布整个互联网,包括 SO,我在几天内查看了数百篇文章,但我似乎无法跨过这最后一道障碍。
我正在使用带有 Identity 的开箱即用的 dotnet react 项目。(dotnet 5.0)。我还添加了 Microsoft 登录。
身份验证工作得很好。对于任一登录类型,我都可以使用 [Authorize] 保护资源。
但是尽我所能,每次添加角色时都会出现403错误;即[授权(角色=“管理员”)]
我添加了一些虚拟用户来尝试一下,然后添加了一些代码来添加角色。这是代码:
public async Task SetupRoles()
{
string[] roleNames = { "Admin", "Office" };
foreach (var roleName in roleNames)
{
var roleExist = await _roleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
var newRole = new IdentityRole(roleName);
//await _roleManager.CreateAsync(newRole);
//await _roleManager.AddClaimAsync(newRole, new Claim(ClaimTypes.Role, roleName));
}
}
var user = await _userManager.FindByEmailAsync("me@me.com");
if (user != null)
{
var result = await _userManager.AddToRoleAsync(user, "Admin");
await _userManager.AddToRoleAsync(user, "Office");
//await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, "Admin"));
//await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, "Office"));
}
}
我在尝试添加失败的代码中留下了注释。这段代码在标准 MVC 项目中完美运行,因为我从那里复制了它!
我添加了一个来自 SO 的 IProfileService 类:
public class MyProfileService : IProfileService
{
public MyProfileService()
{ }
public Task GetProfileDataAsync(ProfileDataRequestContext context)
{
//get role claims from ClaimsPrincipal
var claims = context.Subject.FindAll(JwtClaimTypes.Role);
//add your role claims
context.IssuedClaims.AddRange(claims);
return Task.CompletedTask;
}
public Task IsActiveAsync(IsActiveContext context)
{
// await base.IsActiveAsync(context);
return Task.CompletedTask;
}
}
我在 ConfigureServices 中的 Startup.cs 看起来像这样:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext <OfficeManagerContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddDefaultIdentity<ApplicationUser>(options =>
options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>()
.AddProfileService<MyProfileService>();
services.AddAuthentication()
.AddIdentityServerJwt()
.AddMicrosoftAccount(microsoftOptions =>
{
microsoftOptions.ClientId = Configuration["AzureAd:ClientId"];
microsoftOptions.ClientSecret = Configuration["AzureAd:ClientSecret"];
});
services.AddAuthorization();
...
这是在 API 调用中发送的令牌:
{
"nbf": 1627003083,
"exp": 1627006683,
"iss": "https://localhost:44340",
"aud": "OfficeManager.AlphaAPI",
"client_id": "OfficeManager.Alpha",
"sub": "*******-b0ac3839766c",
"auth_time": 1627003080,
"idp": "local",
"role": [
"Office",
"Admin"
],
"jti": "***",
"sid": "***",
"iat": 1627003083,
"scope": [
"OfficeManager.AlphaAPI",
"openid",
"profile"
],
"amr": [
"pwd"
]
}
最后,这是控制器,即股票 WeatherForecastController
[ApiController]
[Authorize(Roles = "Admin")]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
....
重复一遍,如果我删除 Authorize 的 Roles 部分,它工作正常。使用角色,我收到 403 错误。
画面越来越模糊!!!请帮忙 !!!
我已经合并了我能找到的所有内容,并且从所有方面来看,这应该可以工作,但显然我是个白痴并且遗漏了一些东西。
谢谢
解决方案
推荐阅读
- android - 将文件从 /Downloads 复制到内部 /cache 文件夹
- unix - 对 C/C++ 进程的 PS 命令:rssize 占用的内存比 vsize 多?
- acumatica - 从 Acumatica 21R1 中的 Visual Studio 编译自定义项目后出现错误
- python - 创建一个 python 桌面应用程序来导航和查看 S3 文件而不使用 aws 凭据
- loops - 保留事件前后连续 5 年出现的观察结果
- php - 为什么我在 php 中使用查询选择时有 2 个值?
- c++ - 使用 Cmake 将 waLBerla 链接到我自己的代码
- amazon-s3 - Gatsby watchMode 和 overlayDrafts 在 S3 静态网站上不起作用
- r - dim(data)[-1] 和 dim(data)[1] 有什么区别
- javascript - React Navigation V6 中的奇怪行为