Authorization / Roles in MVC5

I am having problems using permissions / roles in MVC5 (VS2013).

Authentication works almost completely (this can be said simply by using Visual Studio to create the default MVC project). I am changing the DefaultConnection connection string to a valid (but non-existent) database. Then I register a new user, and the database is created automatically, with tables such as AspNetUsers and AspNetRoles .

However, I cannot do anything with roles. The first thing to do is add a role with C # code, for example:

 Roles.CreateRole("Admin"); 

I get an exception from the message:

'Role Manager is not enabled.'

I include it in web.config with:

 <roleManager enabled="true"/> 

And now get the exception:

'Cannot connect to SQL Server database.

This works very easily with System.Web.Security.SqlRoleProvider , but not with the new provider, which works with MVC5 by default. There are many very complicated articles on this, but it seems to me that this is so important and simple that there should be an easy way to make it work.

Thanks so much for any help.

+6
source share
2 answers

I solved it now. It turns out that the Roles class is completely irrelevant to role management in MVC5, at least in view of the finished configuration.

The Roles class and the Membership class still exist, and the Provider is configured to SqlMembershipProvider .

However, this is NOT the provider used by the AccountController , which does not use the Membership class at all; It uses Microsoft.AspNet.Identity.UserManager .

While the generated AccountController contains many examples of using the UserManager , it does nothing for the roles.

Equivalent class for Microsoft.AspNet.Identity.RoleManager roles. There is full documentation on MSDN for this.

+5
source

I suggest referring to this article as it shows how you can create roles. After you have created all the roles, you can use the UserManager.AddToRole or UserManager.AddToRoleAsync method to add a user to a specific role.

0
source

All Articles