为了测试目的,我想更改当前登录用户的角色,我不知道我可以在哪里做以及如何向当前的索赔集合中添加和删除索赔
一种方法是注册自定义IClaimsTransformation
,您可以在其中创建自定义主体,并根据需要更改其身份/声明/角色。
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;
}
}