asp.net-web-api – 添加角色声明 – 我应该使用IClaimsTransformer

我们想在当前主体中添加很多角色声明(我们使用Authorize(Roles)属性),并找到了看起来非常合适的IClaimsTransformer.

我们这样注册了

 app.UseClaimsTransformation(new ClaimsTransformationOptions
        {
            Transformer = new GetRolesFromDatabaseClaimsTransformer(new RoleManager2(Configuration.GetConnectionString("ourcoolapp")))
        });

变换是这样的:

public Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
{
        // A hacky way to not load on all requests. Better ideas?
        if (!context.Context.Request.Path.Value.Contains("api/"))
        {
            return Task.FromResult(context.Principal);
        }

        var roleClaims = RoleManager.GetRolesForUser(context.Principal.Identity.Name).Select(roleName => new Claim("role", roleName));

        var claims = new List<Claim> { };
        var identity = context.Principal.Identity as ClaimsIdentity;
        claims.AddRange(identity.Claims);
        claims.AddRange(roleClaims);

        var userIdentity = new ClaimsIdentity(claims, "local");
        var userPrinicpal = new ClaimsPrincipal(userIdentity);

        return Task.FromResult(userPrinicpal);
}

问题:是否有替代或更智能的方法来添加角色声明?

谢谢

Larsi

最佳答案 另一种选择可能是
UserClaimsPrincipalFactory

它提供了为给定用户创建声明主体的方法,您可以像ClaimsTransformer一样自定义它.

默认情况下,它会将UserName和UserId添加到声明集合中.
为了自定义它,您可以从UserClaimsPrincipalFactory驱动并覆盖CreateAsync

public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<User, Role>
{
    public AppClaimsPrincipalFactory(UserManager<User> userManager,
        RoleManager<Role> roleManager,
        IOptions<IdentityOptions> optionsAccessor, 
        ILogger<AppClaimsPrincipalFactory> logger) 
        : base(userManager, roleManager, optionsAccessor)
    {
        logger.LogInformation("AppClaimsPrincipalFactory ctor");
    }

    public override async Task<ClaimsPrincipal> CreateAsync(User user)
    {
        var principal = await base.CreateAsync(user);
        ((ClaimsIdentity)principal.Identity).AddClaims(new []
        {
            new Claim("Foo", "Bar"), 
        });

        return principal;
    }
}

并在DI中注册工厂:

services.AddScoped<IUserClaimsPrincipalFactory<User>,  AppClaimsPrincipalFactory>();  

只要用户的声明请求,它就会更改/覆盖声明.
欲了解更多信息,请查看来源于GitHub.

点赞