Tuesday, February 18, 2014

ASP.NET Membership and Role Provider-Part-2


Introduction

How many sites have you seen that requires you to login? I guess the answer to this question is "almost all of them". Well, the idea behind this article is to understand how ASP.NET lets us create sites with an authentication and authorization mechanism in place and how we can use ASP.NET server controls to quickly and efficiently implement this.

Background

When we are working on applications where authentication and authorization is a key requirement, then we will find the ASP.NET roles and membership feature very useful. Authentication means validating users. In this step, we verify user credentials to check whether the person tying to log in is the right one or not. Authorization on the other hand is keeping track of what the current user is allowed to see and what should be hidden from him. It is more like keeping a register to what to show and what not to show to the user.
Whenever a user logs in, he will have to authenticate himself with his credentials. Once he is authenticated, he will be authorized to see resources/pages of the website. Mostly these two concepts go together and ASP.NET provides us with some server controls that provide a lot of boilerplate functionality out of the box. If we use ASP.NET's authentication and authorization mechanism, then we can focus on what should be authorized and who should be authenticated rather than worrying about how to do that.

Using the Code

ASP.NET provides a lot of control that facilitate the authentication mechanism. Some of the controls that ASP.NET provides for authentication are:
  • Login: this lets the user login using his credentials
  • PasswordRecovery: This control lets the user recover his password.
  • CreateUserWizard: This control lets the user to create an account on the website.
  • ChangePasword: This control will allow users to change their passwords.
  • LoginStatus: This will show whether the user is logged in or not.
  • LoginName: This will display the logged in user's name.
For the authorization part, Roles is the mechanism that ASP.NET uses to authorize users. Each user belongs to one or many roles and the web pages of our site are configured against roles. So if a user belongs to a role that is allowed to view a certain page, he will be able to.
Let us now write a small application to see these controls and concepts in action. We will develop a small website that has three types of users - free users, regular users, and premium users. Each type of user will be able to see their respective list of downloads and the download list of the inferior role, i.e., premium could see regular list and free list, regular could see free list, tec. So let us first create the hierarchy of web pages to achieve this.
Roles and Membership Image
So we have created separate folders for each role and the top level will contain the files for free users. Now we will configure these folders' access. We want two Roles in our application: Regular and Premium, rest of the users will be considered free users.
Let us create the Roles using WSAT (Web Site Administration Tool).

How to achieve this Web site Administration Tool step by step procedure just follow the lead:-








Roles and Membership Image
Once we have the Roles created, we can create the access rules.
Roles and Membership Image
This can be done via WSAT or could be done directly from web.config. Following is the web.config configured for "Premium Users".
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
    <system.web>
        <authorization>
            <allow roles="Premium" />
            <deny users="*" />
        </authorization>
    </system.web>
</configuration>
<pre lang="xml">

Once we have done that, we have ensured that the respective folders can only be accessed if the user belongs to a Role. So now obviously the next step would be to create users and assign them Roles.
Before creating users, let's understand that we can use two types of authentication:
  1. Windows authentication: In this type, the users are authenticated on their Windows username and password. This method is least recommended in an internet scenario. In an internet scenario, we should always use "Forms based authentication".
  2. Forms based authentication: In this type of authentication, the user will explicitly have to provide his credentials and these credentials, once verified by the server, will let the user to log in.
So we will be using forms based authentication. We can create users from WSAT and assign them roles.
Roles and Membership Image
Apart from that, we will also create users from the application front-end using ASP.NET server controls. We will have aCreateUserWizard control for that.
Note: We can use the Membership class to perform user management tasks from within the code, such as creating, deleting, or modifying user accounts.
Roles and Membership Image
To assign roles, we will have to do this:
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
    if (RadioButtonList1.SelectedValue == "0")
    {
        string username = CreateUserWizard1.UserName;
        Roles.AddUserToRole(username, "Regular");
    }
    else if (RadioButtonList1.SelectedValue == "1")
    {
        string username = CreateUserWizard1.UserName;
        Roles.AddUserToRole(username, "Premium");
    }
}

We will use a Login control to let the user log in.
Roles and Membership Image
We have also added controls like LoginStatus and LoginName in the navigation region to display the login status and logged in user's name.
Roles and Membership Image
Now let us see what pages are there in our application and which user can access which page (apart from the home page).
Roles and Membership Image
This can be accessed by any user who is not logged in and all Regular and Premium users.
Roles and Membership Image
This page can only be accessed by Regular and Premium users.
Roles and Membership Image
This page can only be accessed by Premium users.
Now we have a basic web application working with Roles configured. This application uses all the ASP.NET provided features for authentication and authorization.

Monday, February 17, 2014


Introduction

ASP.NET 2.0 provides built in controls to manage Membership in Web Applications. All these controls use ASP.NET providers that are loaded via web.config file. Membership provider and Role provider allow a complete system to maintain users information, authenticate and authorize the users. This article demonstrates how to use and configure the default Member ship and Role provider.

Membership and Role Provider

Initially by using the Visual Studio 2005/2008/2010, create an ASP.NET website/web application. If you are using Visual Studio 2010, login and registration pages are available by default in the application. Now to store the user information, we need to create the database in the SQL Server. Follow the steps given below to use built in user store schema for maintaining the user information.
  1. Go to Visual Studio, Visual Studio tools and then open the Visual Studio Command Prompt.
  2. Use the aspnet_regsql.exe command to run the ASP.NET SQL Server Setup Wizard.
  3. Check the option “Configure SQL Server for application services”.
  4. Select the Server Instance and the database name for the application, if the database name is not provided, default aspnetdb database is created.
  5. Click the confirm settings and finish button to create the database store.
Step 1:

Step 2:


Step 3:

Step 4:

Step 5:

Preparing to build the security system for use in application, we need to configure the membership provider inweb.config file. The following settings for Forms Authentication, Membership and Role provider are applied in theweb.config file.

Forms Authentication Settings

The authentication mode under system.web tag is set to “Forms” and the elements included in are loginUrl,defaultUrltimeoutcookieless and protection which specifies the login page URL, default page URL, cookie expiration time and protection level respectively. The settings in web.config file would look similar to the code shown below:

<authentication mode="Forms">
     <forms cookieless="UseCookies" defaultUrl="HomePage.aspx" 
 loginUrl="UnAuthorized.aspx" protection="All" timeout="30">
          </forms>
</authentication>    

Membership Provider Settings

Some of the important elements to be considered in the Membership provider are name – name of the provider, type – namespace of the provider, connectionStringName – name of the connectionstring and the most important password format. The password format is available in three formats, Hashed, Encrypted and Clear. Hashed format provides one way of storing password in encrypted format which cannot be brought back to original state, whereas Encrypted format provides both to encrypt and decrypt the password.
<membership defaultProvider="Demo_MemberShipProvider">
 <providers>
  <add name="Demo_MemberShipProvider"
      type="System.Web.Security.SqlMembershipProvider"
      connectionStringName="cnn"
      enablePasswordRetrieval="false"
      enablePasswordReset="true"
      requiresQuestionAndAnswer="true"
      applicationName="/"
      requiresUniqueEmail="false"
      passwordFormat="Hashed"
      maxInvalidPasswordAttempts="5"
      minRequiredPasswordLength="5"
      minRequiredNonalphanumericCharacters="0"
      passwordAttemptWindow="10" passwordStrengthRegularExpression="">
 </providers>
</membership>

Role Provider Settings

The similar way is to specify the settings for default Provider under system.web tag of the web.config file as shown below. The settings are simple and self explanatory.
<roleManager enabled="true" cacheRolesInCookie="true" 
 cookieName="TBHROLES" defaultProvider="Demo_RoleProvider">
              <providers>
                  <add connectionStringName="dld_connectionstring"
                  applicationName="/" name="Demo_RoleProvider"
                  type="System.Web.Security.SqlRoleProvider, System.Web,
                  Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
             </providers>
</roleManager>