How to use roles in .NET MVC Core

Refresh

2 weeks ago

Views

8 time

2

I have tried for days now to implement roles in a MVC project. I have started a new project and chosen Authentication to "Individual user account". I added the [Authorize] to HomeControllers Indexpage and everything works. To add a role i included:

services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();

to startup.cs ->ConfigureServices and then added a call to following functions from startup->Configure

private async Task CreateRole(IServiceProvider serviceProvider)
{
    var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    IdentityResult roleResult;
    roleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
}

private async Task SetUserAdmin(string username, IServiceProvider serviceProvider)
{
    var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
    IdentityUser user = await UserManager.FindByEmailAsync(username);
    await UserManager.AddToRoleAsync(user, "Admin");
}

this will create the role "Admin" and bind it to a specific user. When i look at the table in the db via:

select * from AspNetRoles
select * from AspNetUsers
select * from AspNetUserRoles

The tables is populated and linked to eachother but when i use [Authorize(Roles="Admin")] error page 401 will appear, but when i read out the roles for the user via:

var roles = await UserManager.GetRolesAsync(await UserManager.FindByEmailAsync(username));

It will return the value "Admin".

What can be the problem? Big thanks for any suggestions!

0 answers