事实证明,您可以创建自己的 ClaimActions,在上面的示例中,我必须执行以下操作:
首先..创建一个新类:
public class RoleClaimAction : ClaimAction
{
private const string RoleClaimType = "role";
public RoleClaimAction() : base(RoleClaimType, ClaimValueTypes.String)
{
}
public override void Run(JsonElement userData, ClaimsIdentity identity, string issuer)
{
//Map array of roles to separate role claims
var roles = userData.TryGetStringArray(RoleClaimType)?.ToList();
if (roles!.Any())
{
foreach (var role in roles!)
{
AddRoleClaim(identity, role, issuer);
}
return;
}
//If we only have one role (not an array), add it as a single role claim
var singleRole = userData.TryGetString(RoleClaimType);
if(!string.IsNullOrEmpty(singleRole))
AddRoleClaim(identity, singleRole, issuer);
}
private void AddRoleClaim(ClaimsIdentity identity, string role, string issuer)
{
identity.AddClaim(new Claim(JwtClaimTypes.Role, role, ClaimValueTypes.String, issuer));
}
}
这将简单地验证用户有一个名为角色的声明,并将数组值重新映射到单独的角色声明,然后“挂钩”到身份验证框架中。
要添加您的 ClaimAction,只需将其添加到您的 OpenIdConnectOptions 中:
options.ClaimActions.Add(new RoleClaimAction())
现在使用角色授权属性,并且 User.IsInRole(string) 应该可以正常工作。