Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authorization/Roles in MVC5

I'm having trouble using authorization/roles in MVC5 (VS2013).

Authentication works pretty much out of the box (that's to say just by using Visual Studio to create the default MVC project). I change the DefaultConnection connection string to a valid (but non-existent) database. I then register a new user and the database is automatically created, with tables such as AspNetUsers and AspNetRoles.

However, I can't seem to do anything with roles. The first thing to do seemed to be to add a role with C# code like:

Roles.CreateRole("Admin");

I get an exception with the message:

'The Role Manager feature has not been enabled.'

I enable it in web.config with:

<roleManager enabled="true"/>

And now get the exception:

'Unable to connect to SQL Server database.'

This used to work very easily with System.Web.Security.SqlRoleProvider, but not with the new provider that comes as default with MVC5. There are lots of very complex articles on this, but it seems to me that it is something so essential and straightforward that there must be a simple way to get it working.

Many thanks for any help.

like image 926
Jasper Kent Avatar asked Dec 30 '13 18:12

Jasper Kent


1 Answers

I've solved this now. It turns out that the Roles class is completely irrelevant to role management in MVC5, at least in terms of the out-of-the-box configuration.

The Roles class and Membership class are still there, with the Provider 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 provides plenty of examples of using UserManager, it does nothing related to roles.

The equivalent class for Roles is Microsoft.AspNet.Identity.RoleManager. There is full documentation for this in MSDN

like image 193
Jasper Kent Avatar answered Oct 11 '22 00:10

Jasper Kent