User.IsInRole return false
Asked Answered
U

5

11

I 'm using Identity 2 for authentication in mvc 5 web site. In my view i want check the role of the user :

@if(User.IsInRole("Customers"))
{
  @*do something*@
}

but this always return false, I have already set <roleManager enabled="true" /> in the web config. any help please.

Unicycle answered 21/5, 2015 at 9:4 Comment(18)
Does your database indicate that the user is definitely in the role and is the role name precisely correct? And is the user definitely logged in? IE... if you add an [Authorize] to the controller, do the actions load?Teresitateressa
The name of the role is correct and its exists in db for this user.Unicycle
If you add [Authorize(Roles = "Customers")] to your action, does the action load? How did you add the user to the role?Teresitateressa
No, it doesn't load. the roles are added in the backend : ApplicationUser user = UserManager.FindById(userId); UserManager.AddToRole(user.Id, roleName);Unicycle
Hmmm very strange. I must admit I didn't know that this method existed until you posted this question.Teresitateressa
did you log out and log back in after you gave the role to user?Rabblement
Yea i'did. in my login action, the role exists : roles = userManager.GetRoles(user.id)Unicycle
@ Coulton which method ?Unicycle
try remove <roleManager enabled="true" /> its not used in asp.net Identity 2Rabblement
i did, still not workingUnicycle
What records do you have in your UserRoles table? Can you verify that the role exists from within the application by running something like (this.RoleManager.FindByNameAsync("Customers").Result != null)Teresitateressa
I The role exists in db, when i change the role to the admin it works fine, i think there is something wrong in role nameUnicycle
The problem was in the role name, it was saved "Customers " with a white space, but i can not understand why when i tried "Customers " it didn't workUnicycle
lol. That takes me back to my original question and is the role name precisely correct :PTeresitateressa
I didn't see the white space, it's not a good idea to work with string, is there another alternative ?another question why i didn't work when I tried "Customers " with a white spaceUnicycle
I guess you could create an Enum and use that instead?Teresitateressa
i think it's better, but i need to add an new field to the enum each time i want to add a new role in the backendUnicycle
another question, how can i create a custom role, for example : I have a list of companies, each company has an analyst, only the analyst of the company can edit it, I want create a custom role that check if the current user is the analyst of the company [Authorize(Roles = "Analyst")]Unicycle
T
12

I just got it to work with my setup that is also using Identity Framework.

I added a user to a role by using the following code:

this.RoleManager.CreateAsync(new Role() {Name  = "Customers"});

this.UserManager.AddToRoleAsync(this.User.Identity.GetUserId<int>(), "Amazing");

Then any time after that, when I ran User.IsInRole("Customers"); it returned false, that was until I relogged them back in.

You need to re-log in the user after having added the user to the role. The role information is stored in the cookies.

I ran the following to log the user again:

var user = await this.UserManager.FindByNameAsync("bob");
var identity = await this.UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

this.AuthManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);

From this point, User.IsInRole("Customers") worked for me and returned true.

This won't work though unless you can verify within your application that it is aware of the role that you want to add them to. You can verify the existence of the role "Customers" by using your RoleManager in the following way:

var roleExists = (this.RoleManager.FindByNameAsync("Customers").Result != null);
Teresitateressa answered 21/5, 2015 at 9:48 Comment(1)
Re-log in fixed my issue thanks..Airmail
K
4

For me the problem is in Startup class i didn't register Roles store like this

services.AddDefaultIdentity<ApplicationUser>() .AddEntityFrameworkStores<ApplicationDbContext>();

so just add .AddRoles<IdentityRole>() and it'll solve the problem for me

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

Kumquat answered 15/5, 2020 at 9:54 Comment(1)
This fixed my issue - Thanks! Would have been nice if this was included creating a new project bootstrapped with authentication :(Brisance
H
1

I have the same problem since I customize the IdentityDbContext class. And the reason why the User.IsInRole("Customers") is always false in my case is because I have the EF lazy loading turned off on my custom context class. I tried to turn on the lazy loading than I logged out and then in, and the User.IsInRole is returning the expected value.

public partial class Context : IdentityDbContext<User>
    {
        public Context() : base("name=Context")
        {
            this.Configuration.LazyLoadingEnabled = true;          
        }
Hirai answered 9/3, 2016 at 9:41 Comment(1)
First I thought this was a solution but in my case the malfunction is not deterministic. According to my debug the LazyLoadingEnabled = true; is the default (MVC 5)Determinable
R
0

recently I was facing the same issue in my case I was running the application without SSl so my browser was rejecting the cookies running the application after enabling SSL solved the issue for me

Romanesque answered 2/1, 2021 at 10:6 Comment(0)
I
0

I tried all the solutions above but nothing worked for me. But then I added this line of code in Program.cs (ASP.NET Core 6) and logged out and logged in again and voila.....it worked. Hope this helps!

services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>>();
Ivanivana answered 28/12, 2023 at 10:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.