Jake_2
Jake_2

Reputation: 78

Roles added to the user does give false in IsInRole

I am trying to use [Authorize(Roles = "Administrator")] But I always get "Access denied".

To test if i added the roles correct i added the following code in my controller:

            var test=User.IsInRole("Administrator");  
            var user = await userManager.GetUserAsync(User);
            var roles =await userManager.GetRolesAsync(user);
            rolesOfUser = roles.ToList();

enter image description here enter image description here

Have I added the role wrong?

Why does IsInRole always return false? is suggesting that the user is not signin or completed all authentication process. If the is the case how do i do that?

Seeding data:

public async Task SeedAsync()
{
    context.Database.EnsureCreated();

    if (await roleManager.RoleExistsAsync("Administrator") == false)
    {
        await roleManager.CreateAsync(new IdentityRole("Administrator"));
    }

    var user = await userManager.FindByEmailAsync("Jakob.Madsen@********.com");
    if (user == null)
    {
        user = new IdentityUser()
        {
            UserName = "Jakob.Madsen@*********.com",
            PhoneNumber = "*********",
            Email = "Jakob.Madsen@*********.com",
        };
        var result = await userManager.CreateAsync(user, "*********");
        if (result == IdentityResult.Success)
        {
            userManager.AddToRoleAsync(user, "Administrator").Wait();
        }
        else
        {
            throw new InvalidOperationException("Could not create Administrator");
        }
    }

    var resultRoles = await userManager.GetRolesAsync(user);
    if (resultRoles.Contains("Administrator") == false)
    {
        userManager.AddToRoleAsync(user, "Administrator").Wait();
    }
}

Update: I follow this ASP .Net Core Identity Role Claims not adding to User as suggested. And it now works.

Upvotes: 0

Views: 157

Answers (1)

Nan Yu
Nan Yu

Reputation: 27578

The IsInRole method and [Authorize(Roles="Administrator")] attribute check whether an identity that this claims principal possesses contains a claim of type ClaimsIdentity.RoleClaimType(http://schemas.microsoft.com/ws/2008/06/identity/claims/role) where the value of the claim is equal to the value specified by the role parameter.

So to summarize, if you call IsInRole, by default the assumption is that your claims representing roles have the type mentioned above – otherwise the role check will not succeed. You can confirm that by listing the claims :

var claims = User.Claims.ToList();

You haven't provide how you seed the roles , but you can find a lot of code samples :

ASP.NET Core 2.0: Getting Started With Identity And Role Management

.NET Core 2.1 Use Role Management

Also don't forget to logout and login again to see the desired behavior .

Upvotes: 2

Related Questions