[使用身份在asp.net核心中调试时为当前用户添加或删除角色?

问题描述 投票:0回答:1

为了测试目的,我想更改当前登录用户的角色,我不知道我可以在哪里做以及如何向当前的索赔集合中添加和删除索赔

.net asp.net-core asp.net-identity claims-based-identity
1个回答
0
投票

一种方法是注册自定义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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.