简体   繁体   English

管理员声明已添加到IdentityUser中,但usermanager不能通过IsInRoleAsync找到它

[英]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. 奇怪的是,已经拥有声明“ admin”的用户仍将被添加为管理员,从而​​有效地在数据库中为他们提供了另一个相同的声明。 After some debugging I found that IsInRoleAsync will always return false. 经过一些调试后,我发现IsInRoleAsync将始终返回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. 我的猜测是,函数IsInRoleAsync不会在表AspNetUserClaims中查找,但是我不确定是否还有另一种方法可以检查此问题。

IsInRoleAsync is failing in your case because you're passing an entire object, rather than the UserId. IsInRoleAsync在您的情况下失败,因为您传递的是整个对象,而不是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. 因此,您实际上应该传递Gebruiker对象的UserId字段,而不是对象本身。

MSDN MSDN

I've resolved the issue by using GetClaimsAsync: 我已经通过使用GetClaimsAsync解决了该问题:

IList<Claim> claimsUser = await _userManager.GetClaimsAsync(g);
bool isAdmin = claimsUser.FirstOrDefault(c => c.Value == "admin") != null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM