22

How in mvc 5 I can found out role of logged user?

I made the user by this code

    private bool AddUserAndRole()
    {
        IdentityResult ir;
        var rm = new RoleManager<IdentityRole>
            (new RoleStore<IdentityRole>(new ApplicationDbContext()));
        ir = rm.Create(new IdentityRole("admin"));

        var user = new ApplicationUser() { UserName = "Admin" };
        var result = UserManager.Create(user, "somepassword");
        UserManager.AddToRole(user.Id, "admin");

        return true;
     }

After I loggin on site by that user. How in controller I can check if that user have role == "admin" or not? I found only one way which doesnt look works fast.

        var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
        var role = rm.FindByName("admin");
        bool result = User.IsInRole(role.Name); //true

Do we have other ways?

Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
Duke
  • 1,844
  • 2
  • 16
  • 26
  • 2
    use Alex's answer or if your checking if a user should be allowed into the controller/webpage use [Authorize(Roles = "admin")] above your controller. – Casey Sebben Oct 30 '13 at 17:29

1 Answers1

93
bool result = User.IsInRole("admin") 

Much easier. :)

Alex Dresko
  • 5,179
  • 3
  • 37
  • 57