I created a new project containing a custom membership provider and overriding the ValidateUser method from the abstract MembershipProvider class:
public class MyMembershipProvider : MembershipProvider { public override bool ValidateUser(string username, string password) {
Then I connected this provider to my ASP.NET MVC 2 project, adding a link and pointing it to my web.config:
<membership defaultProvider="MyMembershipProvider"> <providers> <clear /> <add name="MyMembershipProvider" applicationName="MyApp" Description="My Membership Provider" passwordFormat="Clear" connectionStringName="MyMembershipConnection" type="MyApp.MyMembershipProvider" /> </providers> </membership>
I need to create my own class that inherits the abstract RoleProvider class and overrides the GetRolesForUser method. Authorization ASP.NET MVC uses this method to determine which roles are assigned to the currently logged-in user and allows the user to allow access to the controller action.
Here are the steps we need to take:
1) Create your own class that inherits the abstract RoleProvider class and overrides the GetRolesForUser method:
public override string[] GetRolesForUser(string username) { SpHelper db = new SpHelper(); DataTable roleNames = null; try { // get roles for this user from DB... roleNames = db.ExecuteDataset(ConnectionManager.ConStr, "sp_GetUserRoles", new MySqlParameter("_userName", username)).Tables[0]; } catch (Exception ex) { throw ex; } string[] roles = new string[roleNames.Rows.Count]; int counter = 0; foreach (DataRow row in roleNames.Rows) { roles[counter] = row["Role_Name"].ToString(); counter++; } return roles; }
2) Connect the role provider with the ASP.NET MVC 2 application through our web.config:
<system.web> ... <roleManager enabled="true" defaultProvider="MyRoleProvider"> <providers> <clear /> <add name="MyRoleProvider" applicationName="MyApp" type="MyApp.MyRoleProvider" connectionStringName="MyMembershipConnection" /> </providers> </roleManager> ... </system.web>
3) Set Authorize (Roles = "xxx, yyy") over the desired controller / action:
[Authorization(Roles = "Customer Manager,Content Editor")] public class MyController : Controller { ...... }
What is it! Now it works!
4) Optional: set your own Authorize attribute so that we can redirect the unwanted role to the AccessDenied page:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] public class MyAuthorizationAttribute : AuthorizeAttribute {
Now we can use our own attribute to redirect our users to access the restricted view:
[MyAuthorization(Roles = "Portal Manager,Content Editor", ViewName = "AccessDenied")] public class DropboxController : Controller { ....... }
What is it! Super Duper!
Here are some of the links that I used to get all this information:
Special Role Provider: http://davidhayden.com/blog/dave/archive/2007/10/17/CreateCustomRoleProviderASPNETRolePermissionsSecurity.aspx
I hope this information helps!