User.IsInRole returns nothing in ASP.NET Core (Repository Pattern implemented)
If anyone (as me) is struggling with this in .Net Core 2.1, this link may help.
In short, if you are using AddDefaultIdentity
like this:
services.AddDefaultIdentity<ApplicationUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
Then Roles won't work as they are not implemented in DefaultIdentity.
What worked for me is replacing it with:
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
Also, if you signed in before above fix, logout and login again, so identity claims are refreshed. Now it should work.
After hours of searching I realized this work with ASP.Net Core when using Azure Active Directory and Roles
User.HasClaim(ClaimTypes.Role,"admin");
This Doesn't
User.IsInRole("admin");
User.IsInRole
is checking the cookie. But you are checking this within the same http request as you sign-in. Cookie is simply not there yet - it will be available on the reply or next request.
At that point you need to use ApplicationUserManager.IsInRoleAsync(TKey userId, string role)
to check against the database.
Starting in .Net Core 2.1 (and also works in 3.1), AddDefaultIdentity
is the same as calling:
AddIdentity
AddDefaultUI
AddDefaultTokenProviders
To add role functionality, go to Startup.cs
under ConfigureServices
you can use .AddRoles
like so:
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>() //<-- This line
.AddEntityFrameworkStores<ApplicationDbContext>();
That's all that is needed. It is crucial to logout and login again as someone mentioned above.
For the record (and just to test), I tried services.AddIdentity
:
IServiceCollection does not contain a defintion for 'AddIdentity'...
and services.AddIdentityCore
(no error until Debug and displaying the page):
InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions).
There may be more you can do to get the latter two working, but the code I posted for AddDefaultIdentity
is all I needed in order to get User.IsInRole
and other role functionality working in .NET Core 2.1 and up to 3.1 thus far.