ASP.NET 要声明的核心用户角色枚举值

ASP.NET Core User role enum value to Claim

我有 angular 12 前端和 ASP.NET Core 5 后端。我正在通过 JWT 令牌转移角色。我希望角色作为整数传递,所以我不硬核角色名称。前端本身将有一个枚举,这将使我更容易进行检查,例如这些水平菜单设置仅供管理员使用if (user.role === Role.Administrator),等等

问题是没有new("role", user.Role)这样的重载。如果我执行 user.Role.ToString(),它会发送 Administrator,这是键而不是值 1

public class User
{
    public string Id { get; set; }
    public string Email { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public Role Role { get; set; }
}

public enum Role
{
    Administrator = 1,
    DepartmentAdministrator = 2,
    User = 3
}

public Task GetProfileDataAsync(ProfileDataRequestContext context)
{
    var sub = context.Subject.GetSubjectId();
    var user = _userRepository.FindById(sub);

    var claims = new List<Claim>
    {
        new("username", user.Username),
        new("email", user.Email),
        new("role", user.Role) // cannot be int
    };

    context.IssuedClaims = claims;

    return Task.CompletedTask;
}

您可以转换枚举:

int role = (int) user.Role;

var claims = new List<Claim>
    {
        new("username", user.Username),
        new("email", user.Email),
        new("role", role.ToString())
    };