0

I'm Working on a project that had authorization implemented with One user has One role. Now we want to convert that relation to many to many but in the asp.net core authorization it went wrong.

[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; }
}
}

while our database and mapping works perfect. the authorization in asp.net core fails.

autorization service:

    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()
    {

    }
}

}

but where getting the exception: enter image description here

Ties Theunissen
  • 136
  • 2
  • 16
  • Have you checked [this](https://stackoverflow.com/questions/50590432/jwt-securitytokeninvalidsignatureexception-using-rs256-pii-is-hidden)? – Muhammad Hannan Oct 01 '20 at 15:40
  • You can see the hidden details in development by adding the following to Configure() in the Startup class: `if (env.IsDevelopment()) { IdentityModelEventSource.ShowPII = true; }` Once you have the full message check the key being used is correct for the token. – Zhi Lv Oct 02 '20 at 06:04
  • Nevermind... I saw my flaw. there is nothing wrong with the code. works as expected. In chrome I have the application 'ModHeader' installed and I overrided the bearer with it. – Ties Theunissen Oct 02 '20 at 11:29

0 Answers0