【发布时间】:2020-02-13 19:15:20
【问题描述】:
出于测试目的,我想更改当前登录用户的角色,我不知道在哪里可以做以及如何在当前声明集合中添加和删除声明
【问题讨论】:
标签: .net asp.net-core asp.net-identity claims-based-identity
出于测试目的,我想更改当前登录用户的角色,我不知道在哪里可以做以及如何在当前声明集合中添加和删除声明
【问题讨论】:
标签: .net asp.net-core asp.net-identity claims-based-identity
一种方法是注册自定义IClaimsTransformation,您可以在其中创建自定义主体并根据需要更改其身份/声明/角色。
IClaimsTransformation 服务(如果存在)将在请求成功验证后调用。
我创建了一个仅在开发环境中生效的自定义转换,如下所示:
public class CustomClaimsTransformation : IClaimsTransformation
{
private readonly IHostingEnvironment env;
// if you're using 3.0, use `IWebHostEnvironment` instead
public CustomClaimsTransformation(IHostingEnvironment env)
{
this.env = env;
}
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
if (!NeedChangeClaims(principal))
return Task.FromResult(principal);
var identity = principal.Identity as ClaimsIdentity;
// filter claims (i.e. remove claims)
var claims= identity.Claims
.Where(c => !ShouldRemoveThisClaim(c));
// map a new identity
identity = new ClaimsIdentity(claims, identity.AuthenticationType, identity.RoleClaimType,identity.NameClaimType);
// add extra claims as you like
identity.AddClaim(new Claim(ClaimTypes.StreetAddress,"NY"));
return Task.FromResult(new ClaimsPrincipal(identity));
}
private bool NeedChangeClaims(ClaimsPrincipal cp)
{
if (env.IsDevelopment()) {
return true;
}
return false;
}
private bool ShouldRemoveThisClaim(Claim c)
{
if (c.Type == ClaimTypes.Role && c.Value == "FIAdmin")
return true;
if (c.Type == ClaimTypes.Role && c.Value == "HRAdmin")
return true;
if (c.Type == ClaimTypes.OtherPhone)
return true;
return false;
}
}
要启用此服务,我们还需要在 Startup 中注册它:
services.AddDefaultIdentity<IdentityUser>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddSingleton<IClaimsTransformation, CustomClaimsTransformation>();
【讨论】: