J86
J86

Reputation: 15237

In JWT Authorization, check if user has role Admin

I am working on a .Net Core API, and inside my Controller, I have the following code:

if (User.Identity.IsAuthenticated)
{
    var username = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
    var user = await _userManager.FindByNameAsync(username);
    artistCardDtoCollection = _artistsService.GetAllArtists(user.Id, User.IsInRole("Admin"));
}

The code above is because I wish to pass the User.Id (if logged in) and a IsAdmin flag to my GetAllArtists method.

The code above is failing on User.IsInRole("Admin"). I get a false when I know 100% that the user in question is an Admin. I've double checked the database via SQL Management Studio.

This makes me think one can't use User.IsInRole() when working with JWT. If that is the case, then what is the correct way? Thanks

Upvotes: 0

Views: 1284

Answers (1)

user2771704
user2771704

Reputation: 6202

Probably it could be the caching issue with User.IsInRole(), if we check documentation we will find:

IsInRole first checks the IsRoleListCached property to determine whether a cached list of role names for the current user is available. If the IsRoleListCached property is true, the cached list is checked for the specified role. If the IsInRole method finds the specified role in the cached list, it returns true. If IsInRole does not find the specified role, it calls the GetRolesForUser method of the default Provider instance to determine whether the user name is associated with a role from the data source for the configured ApplicationName value.

In your case you can try to use GetRolesAsync like below:

var user = await _userManager.FindByNameAsync(username);
var roles = await _userManager.GetRolesAsync(user);
artistCardDtoCollection = _artistsService.GetAllArtists(user.Id, roles.Contains("Admin"));

Upvotes: 2

Related Questions