c# - 如何在 IdentityServer4 中为声明添加角色?
问题描述
我是 IdentityServer 的新手,我整天都在努力解决这个问题。以至于我几乎要放弃这个了。我知道这个问题已经被问了一遍又一遍,我尝试了许多不同的解决方案,但似乎都没有奏效。希望你能帮助我把我推向正确的方向。
首先,我通过运行安装了 IdentityServer4 模板,dotnet new -i identityserver4.templates
并通过运行使用 is4aspid 模板创建了一个新项目dotnet new is4aspid -o IdentityServer
。
之后,我创建了一个新的 IdentityServer 数据库并运行了迁移。到那时,我有一个默认的身份数据库结构。
在 Config.cs 我更改MVC client
为以下内容:
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.Implicit,
ClientSecrets = { new Secret("47C2A9E1-6A76-3A19-F3C0-S37763QB36D9".Sha256()) },
RedirectUris = { "https://localhost:44307/signin-oidc" },
FrontChannelLogoutUri = "https://localhost:44307/signout-oidc",
PostLogoutRedirectUris = { "https://localhost:44307/signout-callback-oidc" },
AllowOfflineAccess = true,
AllowedScopes = { "openid", "profile", "api1", JwtClaimTypes.Role }
},
并将GetApis
方法更改为:
public static IEnumerable<ApiResource> GetApis()
{
return new ApiResource[]
{
new ApiResource("api1", "My API #1", new List<string>() { "role" })
};
}
当然,数据库中还没有用户,所以我添加了一个注册表单并注册了两个虚拟用户,一个是用户名admin@example.com
,一个是用户名subscriber@example.com
。
为了将角色分配给这些用户,我在 Startup.cs 中创建了以下方法。
private async Task CreateUserRoles(IServiceProvider serviceProvider) {
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
IdentityResult adminRoleResult;
IdentityResult subscriberRoleResult;
bool adminRoleExists = await RoleManager.RoleExistsAsync("Admin");
bool subscriberRoleExists = await RoleManager.RoleExistsAsync("Subscriber");
if (!adminRoleExists) {
adminRoleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
}
if(!subscriberRoleExists) {
subscriberRoleResult = await RoleManager.CreateAsync(new IdentityRole("Subscriber"));
}
ApplicationUser userToMakeAdmin = await UserManager.FindByNameAsync("admin@example.com");
await UserManager.AddToRoleAsync(userToMakeAdmin, "Admin");
ApplicationUser userToMakeSubscriber = await UserManager.FindByNameAsync("subscriber@example.com");
await UserManager.AddToRoleAsync(userToMakeSubscriber, "Subscriber");
}
在Configure
同一个类的方法中,我添加了参数IServiceProvider services
并像这样调用上述方法:CreateUserRoles(services).Wait();
. 到这个时候,我的数据库确实有两个角色。
接下来,我创建了一个新的解决方案(在同一个项目中),并在该解决方案的 Startup.cs 文件中添加了以下ConfigureServices
方法。
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options => {
options.SaveTokens = true;
options.ClientId = "mvc";
options.ClientSecret = "32D7A7W0-0ALN-2Q44-A1H4-A37990NN83BP";
options.RequireHttpsMetadata = false;
options.Authority = "http://localhost:5000/";
options.ClaimActions.MapJsonKey("role", "role");
});
之后我添加了同一个类app.UseAuthentication();
的Configure
方法。
然后我使用以下 if 语句创建了一个新页面。
if(User.Identity.IsAuthenticated) {
<div>Yes, user is authenticated</div>
}
if(User.IsInRole("ADMIN")) {
<div>Yes, user is admin</div>
}
我登录admin@example.com
但第二个 if 语句返回False
。我通过像这样遍历它们来检查所有声明。
@foreach (var claim in User.Claims) {
<dt>@claim.Type</dt>
<dd>@claim.Value</dd>
}
但是没有找到角色声明,只有 sid、sub、idp、preferred_username 和 name。
我试图在那里获得这个角色,以便第二个 if 语句返回 True 但在尝试和尝试之后我还不能让它工作。有人可以看到我必须做什么才能完成这项工作吗?我是 IdentityServer4 的绝对初学者,并尽我所能理解它。任何帮助将不胜感激。提前致谢!
编辑1:
多亏了这个问题和这个问题,我感觉自己走在正确的轨道上。我做了一些修改,但我仍然无法让它工作。我刚刚尝试了以下。
- 在我的 IdentityServer 项目中创建了一个新的 ProfileService 类,其内容如下。
public class MyProfileService : IProfileService {
public MyProfileService() { }
public Task GetProfileDataAsync(ProfileDataRequestContext context) {
var roleClaims = context.Subject.FindAll(JwtClaimTypes.Role);
List<string> list = context.RequestedClaimTypes.ToList();
context.IssuedClaims.AddRange(roleClaims);
return Task.CompletedTask;
}
public Task IsActiveAsync(IsActiveContext context) {
return Task.CompletedTask;
}
}
接下来我在 ConfigureServices 方法中注册了这个类,方法是添加services.AddTransient<IProfileService, MyProfileService>();
. 之后,我在 GetIdentityResources 方法中添加了一个新行,现在看起来像这样。
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResource("roles", new[] { "role" })
};
}
我还将角色添加到我的 Mvc 客户端,如下所示AllowedScopes = { "openid", "profile", "api1", "roles" }
:
接下来,我切换到另一个项目并在 .AddOpenIdConnect oidc 中添加了以下几行。
options.ClaimActions.MapJsonKey("role", "role", "role");
options.TokenValidationParameters.RoleClaimType = "role";
但是,我仍然无法让它像我想要的那样工作。有人知道我错过了什么吗?
解决方案
您需要做两件事来确保您将在声明中获得用户角色:
1- 在 IdentityServer4 项目中:您需要实现 IProfileService http://docs.identityserver.io/en/latest/reference/profileservice.html
不要忘记像这样在 startup.cs 文件中添加类
services.AddIdentityServer()
// I just removed some other configurations for clarity
**.AddProfileService<IdentityProfileService>();**
2- 在 Web Client 项目的 startup.cs 文件中:配置 openId 时,您必须提及:
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "Identity URL ";
options.RequireHttpsMetadata = true;
options.ClientId = "saas_crm_webclient";
options.ClientSecret = "49C1A7E1-0C79-4A89-A3D6-A37998FB86B0";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = false;
options.Scope.Add("test.api");
options.Scope.Add("identity.api");
options.Scope.Add("offline_access");
**options.ClaimActions.Add(new JsonKeyClaimAction("role", null, "role"));**
**options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role"
};**
});
推荐阅读
- docker - kube pod 上的网络问题
- android - android - 片段中的 NFC,在我从另一个活动返回后不会调用 onNewIntent
- android - 更新应用程序不会替换 .\assets\internal 中的文件
- sqitch - sqitch中的依赖关系有什么意义?
- excel - 嵌套 OR 函数
- python - 在 Popen 调用之间保持环境
- domain-driven-design - 使用 CQRS DDD 在事件之后循环命令
- linux - 翻转 YAML 文件内容,使最新的行位于顶部
- java - 使用弹簧靴处理增加吞吐量的情况?
- scala - 如何使用 play-json 读取/写入 case 对象的 trait