i

ASP.Net A Complete Guide

Membership and Roles in Asp.net

Membership and Roles

The membership allows us to create Web sites that will help users to create a unique user name and password combinations. Using this, any user can establish an account with the site. The membership requires a SQL Server database to store the user information. This also includes methods for prompting with a question to users who have forgotten their password.

A practical example of Membership and Role Provider:

For implementing Membership and Role, we need to create an empty website.

Go to the visual studio and Add → New->Project.

When you click on the Project below window will get open.

When you provide the website name and click on the Ok button & it will create a new empty web site.

To store user data, we require tables, sp, and other information. To create membership tables and SP’s follow the below steps.

Go to the folder C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319.you will see the file there as provided in below image.

Click on that the selected file. It will open the window like below.

Click on the next button to continue.

 

You will see the window like above. Select the first option from that.

We can see in the above image the details of "Server" and the "Database name."

Click on the Next button, and one window will get appear. Click on the finish button, so the import wizard gets complete.

Create a Connection String for the connection:

To access the membership information, we need to create a connection string. This will help us to retrieve the information.

<connectionstrings>

 

<addname="applicationservices" connectionstring="data source="Varsha;Initial" catalog="aspnetdb;" user="" id="sa;Password=sa"providerName="System.Data.SqlClient"/">

</addname="applicationservices" connectionstring="data>

 

</connectionstrings>

 

Implement The Authentication: We need to provide the authentication information. Here we are using the form authentication.

Add the following portion in web.config file to enable form authentication.

<authentication mode="Forms">

    <forms cookieless="AutoDetect" defaultUrl="Index.aspx" loginUrl="UnAuthorized.aspx" protection="All" timeout="300">

    </forms>

</authentication> 

 

Add a Login Form:

To display the Login page, we need to add that first.

The below image shows the HTML for the login page.

The users can be authenticated by using the Login1_Authenticate event of the Login control.

protected void Login1_Authenticate(object sender,AuthenticateEventArgs e)

{

 if (Membership.ValidateUser(Login1.UserName, Login1.Password) == true)

    {

        Login1.Visible = true;

        Session["user"] = User.Identity.Name;

        FormsAuthentication.RedirectFromLoginPage(Login1.UserName, true);

    }

 else

    {

        Response.Write("Unauthorized User");

    }

}

 

Add Register Form:

When we created the web site, then there will not be the user. We should add the first user. So we must create some users. For performing this operation of adding new users, we need to add another page called Register.aspx page.

As you can see in the below window, we are adding Register.aspx page for registering the user in the system.

Below code, snippet shows the registration page HTML.

User registration can be created by using the “CreateUserWizard1" counter. I have added the below code to the event.

protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)

{

     MembershipCreateStatus p = MembershipCreateStatus.Success;

     Membership.CreateUser(CreateUserWizard1.UserName,  CreateUserWizard1.Password, CreateUserWizard1.Email,

     CreateUserWizard1.Question, CreateUserWizard1.Answer, true, out p);

}

 

Now run the application. You will see the following login screen.

 

Add Role Manager:

To add role manager add the following code snippet to web.config file.

<rolemanager enabled="true">

      <providers>

        <clear>

        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionstringname="ApplicationServices" applicationname="/">

</add>

        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationname="/">

</add>

    </clear>

      <providers>

</rolemanager>

 

Now we will write the required code for Create, delete roles & assign users to the role.

Creating Roles:

Add the following code for corresponding events to create a role. I have added the code for the corresponding Create button event.

Public void createRoles()

{

        if (!Roles.RoleExists(txtrolename.Text))

        {

            Roles.CreateRole(txtrolename.Text);

            BindUsers();

            BindRoles();

            Label1.Text = "Role has been created Successfully";

        }

        else

        {

            Label1.Text = "Role already exists in the syatem";

        }

}

 

BindRoles

The BindRoles function is used to bind the available roles from the system to the user control.

public void BindRoles()

{

    SqlDataAdapter da = new SqlDataAdapter("select RoleName from aspnet_Roles", cnn);

    DataSet ds = new DataSet();

    da.Fill(ds, "Roles");

    NewLstRoles.DataSource = ds;

    NewLstRoles.DataTextField = "RoleName";

    NewLstRoles.DataValueField = "RoleName";

    NewLstRoles.DataBind();

}

 

BindUsers:

The BindUsers function is used to bind the available user from the system to the role control.

public void BindUsers()

{

    SqlDataAdapter da = new SqlDataAdapter("select UserName from aspnet_users", cnn);

    DataSet ds = new DataSet();

    da.Fill(ds, "Roles");

    NewLstusers.DataSource = ds;

    NewLstusers.DataTextField = "UserName";

    NewLstRoles.DataValueField = "RoleName";

    NewLstusers.DataBind();

 

}

 

Assign Roles to the User

I have added the below code to show how we can assign a role to the user.

 

private void AssignRoles()

    {

            if (!Roles.IsUserInRole(lstRoles.SelectedItem.Text))

            {

                Roles.AddUserToRole(lstusers.SelectedItem.Text,

                                                lstRoles.SelectedItem.Text);

                BindUsers();

                BindRoles();

                Label1.Text = "User has been assigned successfully";

            }

            else

            {

                Label1.Text = "Roles has been assigned already to the User";

            }

    }

 

 

Delete Roles

The code is used to delete the existing Roles if they are not in use.

public void RemoveRole()

{

            Roles.DeleteRole(NewLstRoles.SelectedItem.Text);

            BindUsers();

            BindRoles();

            Label1.Text = "Role has been removed successfully";

}