如何从 ASP.NET 核心身份中自动检索角色?

How to automatically retrieve roles from ASP.NET Core identity?

我正在将我的步骤转移到 OpenIDDict,并且我基于 Velusia 示例制作了我的应用程序。

一切正常,但我有一个问题:我的访问令牌不包含角色。

有一种方法可以自动检索 .NET Core 身份用户角色,并在访问我的控制器中的操作之前将它们附加到用户 属性 作为声明?

一切的目的都是为了能够使用(举例)

User.IsInRole("MyRole");

谢谢大家!

阅读此 post 让我朝着正确的方向前进:Is there a way to dynamically load claims in OpenIddict?

    public class MyClaimTransformation : IClaimsTransformation
{
    private readonly UserManager<UserInfo> _userManager;
    public MyClaimTransformation(UserManager<UserInfo> userManager)
    {
        _userManager = userManager;
    }

    public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        ClaimsIdentity claimsIdentity = new ClaimsIdentity();
        //claimsIdentity.RoleClaimType = OpenIddict.Abstractions.OpenIddictConstants.Claims.Role;
        //claimsIdentity.NameClaimType = OpenIddict.Abstractions.OpenIddictConstants.Claims.Name;

        var claimType = ClaimTypes.Role;


        if (principal.Identity != null && principal.Identity.IsAuthenticated)
        {
            //Do I already have roles in the claim?
            var roleClaimsAvailable = principal.Claims.Any(x => x.Type == claimType);
            if (!roleClaimsAvailable)
            {
                //Roles not found, adding:
                var userProfile = await _userManager.GetUserAsync(principal);
                if (userProfile != null)
                {
                    var roles = await _userManager.GetRolesAsync(userProfile);
                    foreach (var role in roles)
                    {
                        claimsIdentity.AddClaim(new Claim(claimType, role));
                    }

                    principal.AddIdentity(claimsIdentity);
                }
            }
        }

        return principal;
    }

}

我们需要在 Startup.cs 中注册为服务:

//Adding roles on access token incoming
builder.Services.AddTransient<IClaimsTransformation, MyClaimTransformation>();