Custom Membership Provider
To create a custom membership provider, inherit the MembershipProvider abstract class and override the ValidateUser method to verify user credentials against your intended data source. Consider the following example:
public class MyMembershipProvider : MembershipProvider { public override bool ValidateUser(string username, string password) { // Validate user credentials against your database here. var oUserProvider = new MyUserProvider(); return oUserProvider.ValidateUser(username,password,CurrentTerritoryID); } }
Integrate the provider into ASP.NET MVC 2 by adding a reference and configuring it in 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>
Custom Role Provider
For role-based authorization, create a class that inherits the RoleProvider abstract class and overrides the GetRolesForUser method.
public override string[] GetRolesForUser(string username) { // Fetch user roles from the database here. SpHelper db = new SpHelper(); DataTable roleNames = null; try { 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; }
Configure the role provider in 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>
Authorization
Use the [Authorize(Roles="xxx,yyy")] attribute to protect controllers and actions for specific roles.
Custom Authorization Attribute (Optional)
To redirect unauthorized users to an AccessDenied page, create a custom [MyAuthorization] attribute:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] public class MyAuthorizationAttribute : AuthorizeAttribute { // ... Implementation }
Use the attribute as follows:
[MyAuthorization(Roles = "Portal Manager,Content Editor", ViewName = "AccessDenied")] public class DropboxController : Controller { ....... }
The above is the detailed content of How to Implement Custom Membership and Role Providers in ASP.NET MVC 2?. For more information, please follow other related articles on the PHP Chinese website!