Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User.IsInRole return false

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.

like image 376
Hakim Belekacemi Avatar asked May 21 '15 09:05

Hakim Belekacemi


3 Answers

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);
like image 110
Luke Avatar answered Nov 14 '22 09:11

Luke


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;          
        }
like image 23
José Silva Avatar answered Nov 14 '22 11:11

José Silva


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>();

like image 2
Zubair Khakwani Avatar answered Nov 14 '22 09:11

Zubair Khakwani