相关疑难解决方法(0)

添加角色声明-我应该使用IClaimsTransformer吗

我们想在当前主体中添加很多角色声明(我们使用Authorize(Roles)属性),并发现IClaimsTransformer这看起来很合适。

我们已经registerd像这样

 app.UseClaimsTransformation(new ClaimsTransformationOptions
        {
            Transformer = new GetRolesFromDatabaseClaimsTransformer(new RoleManager2(Configuration.GetConnectionString("ourcoolapp")))
        });
Run Code Online (Sandbox Code Playgroud)

而变换是这样的:

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);
}
Run Code Online (Sandbox Code Playgroud)

问题:是否有其他或更聪明的方法来添加角色声明?

谢谢

Larsi

claims-based-identity authorize-attribute asp.net-web-api asp.net-identity .net-core

5
推荐指数
1
解决办法
753
查看次数