Nova Development
Nova Development

Reputation: 57

Use Roles in ASP.NET MVC 5 Identity 2.0

For the life of me I cannot figure out how to simply add roles to my MVC 5 application. This was such a breeze in MVC 4.

The tables are there out of the box, AspNetRoles, which has an Id and Name ("Admin", "User", etc...) AspNetUsers, which has an Id and other user fields AspNetUserRoles - this table has a UserId and RoleId, which is mapped to the tables above.

I want to be able to check to see if a signed in user has the "admin" role or just a "user" role.

Here is what I have tried:

if (User.IsInRole("Admin"))
{
 //do something
}

The value always come back false.

I also tried:

var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var userRole = UserManager.GetRoles(user.GetUserId());
if (userRole[0] == "Admin")
    {
     // do something
    }

This throws error :

"Index was out of range. Must be non-negative and less than the size of the collection."

Is there a simple method that can get the role for the current logged in user? I have seen references to using Role Manager, but I have been unable to get that to work. I believe that was for Identity 1.0

Thanks

Upvotes: 2

Views: 3386

Answers (2)

Diin
Diin

Reputation: 585

I had a similar problem. Using MySQL and I had this in my config file:

<providers>
  <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>

changed to:

<providers>
  <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
</providers>

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239220

The error is telling you that userRole is empty, as even an index of 0, is not "less than the size of the collection". That means, the user in question does not belong to any roles.

The methodology for this is really not much different than it ever has been. The role must exist, first, and the user needs to be associated with that role. As a result, the first step is to populate your roles:

db.Roles.Add(new Role { Name = "Admin" });

You can use RoleManager for this, but I find that to be overkill when you can just utilize the context directly.

Then:

UserManager.AddToRole(userId, "Admin");

That's literally all there is to it. If you like, you can override Seed in Migrations\Configuration.cs to seed some users/roles into the database automatically. For roles, that would just look like:

context.Roles.AddOrUpdate(
    r => r.Name,
    new Role { Name = "Admin" },
    ...
);

Upvotes: 4

Related Questions