Creating an ASP.NET Application With Membership for User Login

MinalS's Avatar author of Creating an ASP.NET Application With Membership for User Login
ASP.NET membership enables use of different membership providers bundled with ASP.NET framework or custom membership providers in an application..
ASP.NET membership is used to enable users to easily use different number of membership providers for the applications. User can use the membership providers that are included in the framework or by adding own providers. The element of membership is the sub element of the system.web section.

The user added in the system is managed through the web.config file. The <credentials> element is present in the config file. But if the user wants to add the users at the design time, the <credentials> element is used. For the modifications of the users they need to be manually added, deleted or removed from the file. If we want to add, delete or modify the users at the runtime the Membership class is used. To implement the class, you need to use the System.Web.Security namespace.

The Membership class has various static methods that allow managing users at the runtime. The list of some of the static methods is mentioned below:
  1. CreateUser: It adds the new user to the database application
  2. DeleteUser: It deletes an existing user from the database
  3. GetUser: It gets the information from the data source of the membership users associated with the unique identifier
  4. GetAllUsers: It gets a collection that represents all the users in the database
  5. UpdateUser: It updates the information for a specific user
  6. ValidateUser: It validates the supplied user name and password
Consider an example of the membership user in ASP.NET. The user can be added using the Membership class.

The source view code of the form is as shown below:
Code:
<div>
<asp:Label ID=”lbl1” runat=”server” Text=”UserName”></asp:Label>
<asp:TextBox ID=”txt1” runat=”server”></asp:TextBox>
<br/>

<asp:Label ID=”lbl2” runat=”server” Text=”Password”></asp:Label>
<asp:TextBox ID=”txt2” runat=”server” TextMode=”Password” ></asp:TextBox>
<br/>

<asp:Label ID=”lbl3” runat=”server” Text=”Email”></asp:Label>
<asp:TextBox ID=”txt3” runat=”server”></asp:TextBox>
<br/>

<asp:Label ID=”lbl4” runat=”server” Text=”password Question”></asp:Label>
<asp:TextBox ID=”txt4” runat=”server”></asp:TextBox>
<br/>

<asp:Label ID=”lbl5” runat=”server” Text=”password answer”></asp:Label>
<asp:TextBox ID=”txt5” runat=”server”></asp:TextBox>
           <br/>

           <asp:Button ID=”btn1” runat=”server” Text=”AddUser” onclick=”btn1_Click” />
</div>
The code behind file contains the following code.

Code:
protected void btn1_Click ( object sender, EventArgs e) {
    MembershipCreateStatus result;
    try {
        MembershipUser newUser=Membership.CreateUser ( txt1.Text, txt2.Text, txt3.Text, txt4.Text, txt5.Text, true, out result);
        if ( result==MembershipCreateStatus.Success) {
            Response.Write( “User Successfully created”);
        } else {
            Response.Write( “User cannot be created”);
        }
    }
    catch (Exception er) {
        Response.Write ( er.Message);
    }
}
The output for the above code is as shown below:



Configuring the Membership Provider



User can configure the membership provider to customize the membership settings. To configure the membership provider, user needs to add the <membership> element to the web.config file. All the custom settings are defined inside the <membership> element as shown in the following example.
Code:
<membership defualtProvider=”CustomMembershipProvider”>
   <providers>
        <clear/>
            <add
                 name=”CustomMembershipProvider”
                 type=”System.Web.Security.SqlMembershipProvider”
                 connectionStringName=”MySqlServer1”
                 enablePasswordRetrieval=”true”
                 enablePasswordReset=”true”
                 requiresQuestionandAnswer=”true”
                 minRequiredPasswordLength=”5”
                 minRequiredNonalphanumericCharacters=”0”
                 passwordFormat=”Hashed” />
    </providers>
</membership>
In the above example, the membership provider is configured. The <add> element in the example contains the following attributes:
  1. Name: It specifies a name for the membership provider. It is mandatory.
  2. type: It specifies a type for the membership provider. It is mandatory.
  3. connectionStringName: It specified the name of the connection string setting. The name must correspond to the connection string defined in the <connectionStrings> section. It is mandatory.
  4. enablePasswordRetrieval: It determines whether the password can be retrieved in case the user forgets it.
  5. enablePasswordReset: It determines whether a password can be reset.
  6. requiresQuestionAndAnswer: It determines whether the membership security answer will be required when requesting or resetting the password. It is optional.
  7. minRequiredPasswordLength: It specifies the minimum length of a password.
  8. minRequiredNonaplhanumericCharacters: It specifies the minimum number of characters that the password should contain. It is optional.
  9. passwordFormat: It specifies the format in which they are stored in the database. The values can be clear, hashed, and Encrypted.

Configuring Authorization



Authorization is the process of verifying whether the authenticated user has the privileges to access a requested resource. After creating the users, the access to the application can be assigned through the membership management service.

Maintaining the set of settings for an individual user is difficult. The users are assembled into groups called as roles and the permissions are defined on these roles. The role management service allows creating roles, assigning users to each role, and restricting user access based on these roles.

To use the role – based authorization in the web application, user needs to enable the <roleManager> element in the web.config file as shown below:
Code:
<configuration>
     <system.web>
        <role Manager enabled=”true” />
              …..
     </system.web>
</configuration>
In the above markup, the value of the enabled attribute is set to true. It enables the role based authorization for the web application.

Creating and Assigning Roles



After the user has enabled the role management service, the roles needs to be created. They can be Users, Administrator, and Guest. One or more roles can be assigned to the users.

ASP.NET provides with the Roles class that helps to create roles. The Roles class contains a number of methods that helps to modify the role information. The list of role methods is mentioned below:
  1. CreateRole: It adds a new role to the data source.
  2. DeleteCookie: It deletes a cookie where the role names are cached
  3. DeleteRole: It removes the role from data source
  4. FindUserInRole: It gets a list of users in the specified role where the user name contains the specified user name to match
  5. GetRolesForUser: It gets a list of roles that has been assigned to the user
The code snippets of the methods are as shown below:
Code:
Roles.CreateRole(“Admin”);
In the above code, Admin role is created.

The following example demonstrates the role creation in ASP.NET.

The source code of the web page is as shown below:
Code:
<asp:Label ID=”lbl1” runat=”server” Text=”CreateRole”></asp:Label>
<br/>
Role Name: <asp:TextBox ID=”txt1” runat=”server”></asp:TextBox>
<br/>
          <asp:Button ID=”btn1” runat=”server” Text=”CreateRole”    OnClick=”CreateRole_OnClick” />
<br/>
        <asp:Label ID=”lbl2” runat=”server”></asp:Label>
<br/>
          <asp:DataList ID=”dt1” runat=”server”>
          <ItemTemplate>
          <%# Container.DataItem.ToString() %>
          </ItemTemplate>
          </asp:DataList>
The code behind file contains the following code.
Code:
public partial class _Default :System.Web.UI.Page {
    string[] rolesarray;
    protected void Page_Load( object sender, EventArgs e) {
        if( !Page.IsPostBack) {
            rolesarray= Roles.GetAllRoles();
            dt1.DataSource=rolesarray;
            dt1.DataBind();
        }
    }
    public void CreateRole_OnClick ( object sender, EventArgs e) {
        string CreateRole=txt1.Text;
        Roles.CreateRole (createRole);
        try {
            if( Roles.RoleExists ( createRole)) {
                lbl2.Text=”Role” +createRole+ ”already exists”;
            }
            Roles.CreateRole(createRole);
            lbl2.Text=”Role” +createRole+” is created”;
            rolesarray= Roles.GetAllRoles();
            dt1.DataSource=rolesarray;
            dt1.DataBind();
        }
        catch (Exception e) {
            lbl1.Text=”Role”+ createRole +”not created”;
            Response.Write(e.ToString());
        }
    }
}
The output for the code is as shown below:


Restricting user access



Once the user has been created and roles are assigned, you can restrict the access of users. You can specify the list of users who are allowed to access the website in the <authorization> element. The element is specified in the web.config file. The element includes two child elements <allow> and <deny>. The list of users who are allowed to access the website are defined in the <allow> tag. The list of users who are not allowed to access the website are added in the <deny> tag.

The attributes of the <allow> and <deny> elements are as follows:
  1. users: It enables to assign the list of users to be granted or denied access. The symbol ? is used to denote the anonymous users and the * symbol denotes as all users.
  2. roles: It enables to assign a list of roles to be granted or denied access.
A web application contains web pages that can be accessed only by specific users. For example, there are certain pages that can be accessed through the administrator. For restricting access to the web pages, these web pages needs to be stored in separate subdirectory. After storing the web pages in the subdirectory, user needs to add a web.config file to that subdirectory. Use the following markup in the web.config file to restrict users having roles other than Admin to access the web pages.
Code:
        <authorization>
             <allow roles=”Admin” />
             <deny users=”*” />
       </authorization>
The markup specifies the users who have been assigned to the Admin role are allowed to access the web pages stored in the subdirectory. All the users having roles other than Admin role are denied access on the web pages.

Configuring Impersonation



When a user requests an ASP.NET application, the request goes to the IIS. IIS authenticates the user and forwards the request to ASP.NET. If ASP.NET impersonation is disabled, irrespective of the user who logged in the system, the application will be executed by using the fixed machine specific account.

The ASP.NET account has permissions such as code compilation and viewing information in any database or files in the application that would not want to grant to the user. For example, if a user visits the current account page, the designer needs to make sure that the information of specific user account is visible. To allow the access to the application according to the permission grated to them, the impersonation is used.

Impersonation is the process of executing code under the authenticated user identity and not under the ASP.NET account. When a user tries to access the web application, the steps for checking the impersonation are followed.

The steps involved are as mentioned below:
  1. When a request is received from a remote client, IIS carries the authentication process. If the client is authenticated, it passes the request to the ASP.NET application.
  2. The application impersonates the client and used the authentication given by IIS to access the restricted resources.
  3. If authorized to access resources, the ASP.NET application returns the requested resources to the client through IIS.
By default the impersonation is disabled in ASP.NET and if not overridden it is inherited by all the applications. When impersonation is disabled, the account used for executing the resources is controlled by the <processmodel> element. User can enable the impersonation in an ASP.NET application by adding the following markup in the <system.web> section of the web.config file.
Code:
<identity impersonate = “true” />
In the above markup, impersonation is enabled for the web application. The application uses the user credentials authenticated by IIS to provide access to the requested resources.

User can enable the web application to run under a specific user identity. User needs to specify the user credentials for the specific user in the web.config file as shown in the following markup.
Code:
<identity impersonate = “true” username=”user1” password=”Password” />
In the above markup, impersonation defines a single specific user account, user1. Therefore, whichever user accesses the application; all the web requests will be grated access according to the permission of the user1 account.
shabbir like this