Search code examples
c#asp.net-coreasp.net-identity

Admin claim added to IdentityUser, but the usermanager does not find it with IsInRoleAsync


I have a piece of code that lets an admin add a new admin via email. I check if the user is in our system. If it is, i check if it's already an admin. The odd part is that users that already have the claim 'admin' will still be added as an admin, effectively giving them another same claim in the database. After some debugging I found that IsInRoleAsync will always return false. What could the cause of this be?

public async Task<IActionResult> VoegAdminToe(VoegAdminToeViewModel vam)
{
    if (ModelState.IsValid)
    {
        Gebruiker g = _gebruikerRepository.GetByEmail(vam.Email);
        if (g != null)
        {
            bool isAdmin = await _userManager.IsInRoleAsync(g, "admin");
            if (!isAdmin)
            {
                await _userManager.AddClaimAsync(g, new Claim(ClaimTypes.Role, "admin"));
                return RedirectToAction(nameof(Index));
            }
            ModelState.AddModelError("GebruikerAlAdmin", "Deze gebruiker is al Admin");

            return View(vam);
        }
        ModelState.AddModelError("GebruikerNull","Deze gebruiker zit niet in het systeem");
        return View(vam);
    }
    else
    {
        return View(vam);

    }
}

My guess would be that the function IsInRoleAsync will not go looking in the table AspNetUserClaims, but I'm not quite sure if there's another method to check for this.


Solution

  • IsInRoleAsync is failing in your case because you're passing an entire object, rather than the UserId.

    bool isAdmin = await _userManager.IsInRoleAsync(g, "admin");
    

    So, you should actually be passing the UserId field of the Gebruiker object, rather than the object itself.

    MSDN