使用IdentityServer4和.NET Core实现基于角色的访问控制 [英] Implement role based access control with IdentityServer4 and .NET Core
问题描述
我们有一个现有的数据库,并且需要使用IdentityServer4和.NET Core实现基于角色的访问控制.
We have an existing database, and need to implement role based access control with IdentityServer4 and .NET Core.
我的问题是:
1 IdenityServer4是否支持RBAC?例如是通过范围声明吗?应该如何实施?
1 Does IdenityServer4 support RBAC? e.g. Is it via scope claim? How should it be implemented?
2我可以使用现有数据库吗?还是我必须创建一个新的数据库?
2 Can I use the existing database? Or Must I create a new database?
任何建议或代码示例都将不胜感激.
Any advice or code sample would be appreciated.
更新
我们实现了资源所有者密码"授予类型和RBAC.
We implement Resource Owner Passowrd grant type and RBAC.
任何建议或指向代码示例的链接都将不胜感激.
Any advice or links to code sample would be appreciated.
推荐答案
在Identity Server上,您可以创建配置文件服务,以使IDS4在颁发令牌时包含role
声明.
On Identity Server side , you can create Profile Service to make IDS4 include role
claim when issuing tokens .
例如,如果使用ASP.NET Identity管理用户/角色,则可以创建配置文件服务,例如:
If example , if using ASP.NET Identity to mange users/roles , you can create profile service like :
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)
{
// await base.IsActiveAsync(context);
return Task.CompletedTask;
}
}
并在Startup.cs中注册:
And register in Startup.cs:
services.AddTransient<IProfileService, MyProfileService>();
在客户端,您应该映射JWT令牌中的角色声明,并尝试在AddOpenIdConnect
中间件中的config下面进行操作:
On client side , you should map the role claim from your JWT Token and try below config in AddOpenIdConnect
middleware :
options.ClaimActions.MapJsonKey("role", "role", "role");
options.TokenValidationParameters.RoleClaimType = "role";
这篇关于使用IdentityServer4和.NET Core实现基于角色的访问控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!