Home > Backend Development > C++ > How to Implement Custom Membership and Role Providers in ASP.NET MVC 2?

How to Implement Custom Membership and Role Providers in ASP.NET MVC 2?

Susan Sarandon
Release: 2025-01-05 06:41:43
Original
911 people have browsed it

How to Implement Custom Membership and Role Providers in ASP.NET MVC 2?

Implementing Custom Membership Provider for ASP.NET MVC 2

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);
    }
}
Copy after login

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>
Copy after login

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;
}
Copy after login

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>
Copy after login

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
}
Copy after login

Use the attribute as follows:

[MyAuthorization(Roles = "Portal Manager,Content Editor", ViewName = "AccessDenied")]
public class DropboxController : Controller
{ 
    .......
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template