Twix
Twix

Reputation: 390

User.IsInRole not working. How to check rolebased authorization?

I am using MVC 5 with EntityFramework 6. In "IdentityModel" I am inheriting IdentityUser class using following code:

public class ApplicationUser : IdentityUser
{
    [Display(Name="First Name")]
    [StringLength(50, ErrorMessage = "Length exceed")]
    public string FirstName { set; get; }

    [Display(Name = "Last Name")]
    [StringLength(50, ErrorMessage = "Length exceed")]
    public string LastName { set; get; }

}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
        this.Configuration.LazyLoadingEnabled = false;
    }


  protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {



        modelBuilder.Entity<IdentityUser>().HasKey(r => r.Id); 
        modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
        modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
        modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });


    }

I have assigned roles to "IdentityUser" using the following code:

UserManager.AddToRole(user.Id, "User");

I can see assigned roles in "IdentityUserRole" table, but when trying to access the roles using

User.IsInRole("User");

It returns always false.

After adding following code in my web.config I get "Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'." this error.

<roleManager enabled="true" defaultProvider="SqlRoleProvider">
  <providers>
    <clear/> 
    <add name="SqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="DefaultConnection"  />
  </providers>
</roleManager>

I am not using code first migration.

Upvotes: 1

Views: 5591

Answers (2)

Anonimys
Anonimys

Reputation: 704

This version work for me:

if (UserManager.IsInRole(User.Identity.GetUserId(), "Admin"))
{
     Response.Write("IS IN ADMIN!");
}

If you want use Authorize attribule with role name like [Authorize(Roles = "Admin")] in your action, i recomend watch this topic:Authorize attribute not working with roles

Upvotes: 0

DavidG
DavidG

Reputation: 119206

User.IsInRole uses the 'old' version of role manager whereas your code is using the newer Identity framework. Instead use the new UserManager (you seem to already have the object):

if (UserManager.IsInRole(user.Id, "Admin"))
{
    //...
}

Upvotes: 3

Related Questions