将单角色管理升级到多角色管理

时间:2020-10-01 13:52:03

标签: asp.net-core authorization many-to-many jwt-auth

我正在一个项目中,该项目的授权已由一个用户实施,并且具有一个角色。 现在,我们希望将这种关系转换为多对多关系,但是在asp.net核心授权中却出错了。

[Serializable]
public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    public Guid? Id { get; set; }
   
    public virtual IList<UserRole> UserRoles { get; set; } = new List<UserRole>();

    [NotMapped]
    public string Token { get; set; }

/**/

[Serializable]
public class UserRole
{
    public Guid UserId { get; set; }
    public User User { get; set; }

    public int RoleId { get; set; }
    public Role Role { get; set; }
}

[Serializable]
public class Role
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [JsonIgnore]
    public int Id { get; set; }

    public string Name { get; set; }
}
}

而我们的数据库和映射可以完美运行。 asp.net核心中的授权失败。

辅导服务:

    public async Task<DTO_User> Authenticate(string username, string password)
    {
        var users = await _userRepo.GetAll();
        var user = users.Where(u => u.Username == (username) && u.Password == (password)).FirstOrDefault();

        if (user == null)
            return null;

        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(_appSettings.Secret);

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Expires = DateTime.UtcNow.AddDays(1),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), 
  SecurityAlgorithms.HmacSha256Signature)
        };

        var claims = new List<Claim>
        {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Username.ToString()),
        };

        var roles = await this._userRepo.GetUserRoles(user.Id.Value.ToString());
        var claimsWithRoles = roles.ToList().Select(role => new Claim(ClaimTypes.Role, role.Name)); 
        var allClaims = claims.Concat(claimsWithRoles);

        tokenDescriptor.Subject = new ClaimsIdentity(allClaims);

        var token = tokenHandler.CreateToken(tokenDescriptor);
        user.Token = tokenHandler.WriteToken(token);

        // remove password before returning
        user.Password = null;

        return _mapper.Map<DTO_User>(user);
    }

**Controller**
[Route("api/[controller]")]
[ApiController]
[Authorize]
[EnableCors("CorsPolicy")]
public class SessionController : ControllerBase
{
    [HttpGet]
    [Route("active")]
    public async Task<IActionResult> GetAllActive()
    {

    }
}

}

但是在哪里出现异常: enter image description here

0 个答案:

没有答案