How to use Roles in ASP.NET Core 2.1?
In addition to the answers already provided, despite adding .AddRoles<Identity>()
, I still could not get Authorization when use Authorize(Roles = "Administrator")
on my controllers. For some reason,the "role claim doesn't seem to affect IsUserInRole or AuthorizeAttribute with a role name."
To make use of roles I would suggest that one use the ASP.NET 2.0 way like below:
services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
This way, you get to use your roles and also get the Identity pages scaffolded for you.
Refer to this issue on aspnet github: Issue 1813
It seems that finally Microsoft understood that not every application needs roles and separated them.
Notice that AddDefaultIdentity
is declared as:
public static IdentityBuilder AddDefaultIdentity<TUser>(this IServiceCollection services) where TUser : class;
So, you can continue to configure Identity options through that IdentityBuilder
. What you want to do is:
services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>();
Fortunately, they also removed the IUser
and IRole
constrains, so now you can use models in a completely separate assembly without having to install hundreds of NuGet packages.
Might help someone else: If you add asp.net identity through scaffolding to an existing project, you'll need to edit the IdentityHostingStartup.cs
and change the services there instead of in your startup class:
services.AddIdentity<AppUser, IdentityRole>()
.AddDefaultUI()
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<authContext>();
And then you can use the role manager in your seeding.