How to use roles in .NET MVC Core


March 2019


47 time


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:


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!

1 answers


How did you add Identity in the startup file? I think it's going wrong with services.AddIdentity.

I use:

services.AddIdentity<IndentityUser, IdentityRole>(options => options.Stores.MaxLengthForKeys = 128)

This is a known bug for .Net Core 2.1 .net core identity 2.1 role authorize not working

Should be solved in 2.2