Form Authentication, Form Authorization and Storing Encrypted Values in Database

Introduction

In this article we will learn Form Authentication and Form Authorization and how to store encrypted values into a SQL database.

Basically Forms Authentication is used for internet web applications where the user does not need to be a member of a domain-based network to have access to any application, websites like gmail.com, facebook.com, twitter.com and so on uses forms authentication because to use these internet applications you do not need to be a member of their domain based network.

Whereas Authorization is the process of determining whether or not an authenticated user has permission to access a specific area of an application.

For example, within our application we'll want to authorize that only users who are logged in can access the Welcome Page.

Let's Start.

  1. Create a new project, name it whatever you want to.

  2. Create three Web Forms and name them as:

    SolutionExplorer
  3. Designing the pages

    Open the Login.aspx page and design it like this:

    Code:

    1. <html xmlns="http://www.w3.org/1999/xhtml">  
    2.      <head runat="server">  
    3.          <title></title>  
    4.      </head>  
    5.      <body>  
    6.          <form id="form1" runat="server">  
    7.              <div>  
    8.                  <fieldset>  
    9.                      < legend>Login</legend>  
    10.    
    11.                      <table>  
    12.                          <tr>  
    13.                              <td>  
    14.                                  <asp:Label ID="lbl_UserName" runat="server" Text="User Name"></asp:Label>  
    15.                              </td>  
    16.                              <td>  
    17.                                  <asp:TextBox ID="tb_UserName" runat="server"></asp:TextBox>  
    18.                             </td>  
    19.                          </tr>  
    20.    
    21.                          <tr>  
    22.                              <td>  
    23.                                  <asp:Label ID="lbl_Password" runat="server" Text="Password"> </asp:Label>  
    24.                              </td>  
    25.                              <td>  
    26.                                  <asp:TextBox ID="tb_Password" runat="server"></asp:TextBox>  
    27.                              </td>   
    28.                          </tr>  
    29.    
    30.                          <tr>  
    31.                              <td colspan="2">  
    32.                                  <asp:Button ID="btn_Login" runat="server" Text="Login" />  
    33.                              </td>  
    34.                          </tr>  
    35.    
    36.                          <tr>  
    37.                              <td colspan="2">  
    38.                                  <asp:Label ID="lbl_Message" runat="server" ForeColor="Red"></asp:Label>  
    39.                              </td>  
    40.                          </tr>  
    41.    
    42.                          <tr>  
    43.                              <td colspan="2">  
    44.                                  <a href="Registration/Register.aspx"> Click here to register</a> if you do not have a user name and password  
    45.                              </td>  
    46.                          </tr>  
    47.    
    48.                      </table>  
    49.                  </fieldset>  
    50.              < /div>  
    51.          </form>  
    52.  </body>  
    53.  </html>  

     

    Open the Register.aspx page and design it like this:

    RegistrationPage

    Code:
    1. <html xmlns="http://www.w3.org/1999/xhtml">  
    2.      <head runat="server">  
    3.          <title></title>  
    4.      </head>  
    5.      <body>  
    6.          <form id="form1" runat="server">  
    7.              <div>  
    8.                  Registration Page  
    9.              </div>  
    10.          </form>  
    11.      </body>  
    12.  </html>  
    Open the Welcome.aspx page and design it like this:

    WelcomePage

    Code:
    1. <html xmlns="http://www.w3.org/1999/xhtml">  
    2.      <head runat="server">  
    3.          <title></title>  
    4.      </head>  
    5.      <body>  
    6.          <form id="form1" runat="server">  
    7.              <div>  
    8.                  <h1>Welcome</h1>  
    9.              </div>  
    10.          </form>  
    11.      </body>  
    12.  </html>  
    Currently a user can easily navigate to any page without using their user name and password just by editing the URL:

    NavigateToAnyPage 
  4. Implementing Form Authentication

    But now we will use a Forms Authentication technique by which only the valid user will be allowed to view other parts of the application.

    To enable Forms Authentication, within the Web.config file use the authentication element <authentication mode=”forms”>.

    Add this code to Web.config file:

    Code:

    1. <system.web>  
    2.      <compilation debug="true" targetFramework="4.0" />  
    3.    
    4.          <authentication mode="Forms">  
    5.              <forms loginUrl="Login.aspx" defaultUrl="Welcome.aspx">  
    6.                  <credentials passwordFormat="Clear">  
    7.                      <user name="jsb" password="jsb"/>  
    8.                      <user name="abc" password="abc"/>  
    9.                  </credentials>  
    10.              </forms>  
    11.          </authentication>  
    12.    
    13.          <authorization>  
    14.              <deny users="?"/>  
    15.          </authorization>  
    16.    
    17.  </system.web>  
    The wildcard ? represents unauthenticated users while * represents all users.
    Open the Login.aspx page in designer mode then double-click on the Login button and add the following code.

    Code:
    1. using System.Web.Security;  
    2.    
    3.  protected void btn_Login_Click(object sender, EventArgs e)  
    4.  {  
    5.      if( FormsAuthentication.Authenticate(tb_UserName.Text, tb_Password.Text))  
    6.      {  
    7.          FormsAuthentication.RedirectFromLoginPage(tb_UserName.Text, false);  
    8.      }  
    9.      else  
    10.      {  
    11.          lbl_Message.Text="Invalid User Name or Password";  
    12.      }  
    13.  }  
    Make a change in the Web.config file from:
    1. <forms loginUrl="Login.aspx">  
    To:
    1. <forms loginUrl="Login.aspx" defaultUrl="Welcome.aspx">  
    Run the project , enter User Name and Password, click on Login.

    LoginPagetwo

    WelcomePageTwo 
  5. Imlementing Form Authorization

    By doing the preceding stuff, we are not able to navigate to the Registration/Register.aspx page if we are not logged in.

    To solve this issue we will be using another Web.config file to the registration folder and specify the authorization element to allow all the users.

    Code:

    1. <system.web>  
    2.      <authorization>  
    3.          <allow users=”*”/>  
    4.      </authorization>  
    5.  </system.web>  
    In your Solution Explorer right-click on the Registration Folder and add a new item as in the following:

    AddNewItemEncrypted

    Once you hit Add you will see a new Web.config file in your project as in the following:

    WebConfigFile

    Add this code to this Web.config file.

    Code:
    1. <?xml version="1.0"?>  
    2.      <configuration>  
    3.          <system.web>  
    4.              <authorization>  
    5.                  <allow users="*"/>  
    6.              </authorization>  
    7.      </system.web>  
    8.  </configuration>  
    Now when you run the project, you will be directed to:

    RegistrationPagetwo
    Since the registration page does not contain anything to register a user, we will design the Registration Page as in the following:

    NewregistrationPage
    Code:
    1. <html xmlns="http://www.w3.org/1999/xhtml">  
    2.      <head id="Head1" runat="server">  
    3.          <title></title>  
    4.      </head>  
    5.      <body>  
    6.          <form id="form1" runat="server">  
    7.              <div>  
    8.                  <table>  
    9.                      <tr>  
    10.                          <td>  
    11.                              <asp:Label ID="lbl_UserName" runat="server" Text="User Name"></asp:Label>  
    12.                          </td>  
    13.                          <td>  
    14.                              <asp:TextBox ID="tb_UserName" runat="server"></asp:TextBox>  
    15.                          </td>  
    16.                          </tr>  
    17.    
    18.                          <tr>  
    19.                              <td>  
    20.                                  <asp:Label ID="lbl_Password" runat="server" Text="Password"></asp:Label>   
    21.                              </td>  
    22.                              <td>  
    23.                                  <asp:TextBox ID="tb_password" runat="server"></asp:TextBox>  
    24.                              </td>  
    25.                          </tr>  
    26.    
    27.                          <tr>  
    28.                              <td>  
    29.                                  <asp:Label ID="lbl_Confpass" runat="server" Text="Confirm Password"></asp:Label>  
    30.                              </td>  
    31.                              <td>  
    32.                                  <asp:TextBox ID="tb_ConfPass" runat="server"></asp:TextBox>  
    33.                              </td>  
    34.                          </tr>  
    35.    
    36.                          <tr>  
    37.                              <td>  
    38.                                  <asp:Label ID="lbl_Email" runat="server" Text="Email"></asp:Label>   
    39.                              </td>  
    40.                              <td>  
    41.                                  <asp:TextBox ID="tb_Email" runat="server"></asp:TextBox>  
    42.                              </td>  
    43.                          </tr>  
    44.    
    45.                          <tr>  
    46.                              <td colspan="2">  
    47.                                  <asp:Label ID="lbl_Message" runat="server" ForeColor="Red"></asp:Label>  
    48.                              </td>  
    49.                          </tr>  
    50.    
    51.                          <tr>  
    52.                              <td colspan="2">  
    53.                                  <asp:Button ID="btn_Register" runat="server" Text="Register"/>  
    54.                              </td>  
    55.                              </tr>  
    56.                  </table>  
    57.              </div>  
    58.          </form>  
    59.      </body>  
    60.  </html>  
  6. Creating a Database in SQL  Server

    Open SQL Server and create a new database “mysamle” as in the following:

    CreateDatabase

    Create a new Table “tblUsers” in the mysamle database as in the following:

    Createtable

    Check wheteher or not the table was created.

    CheckedTable

    Create a Stored Procedure and name it “spRegisterUser”.

    StoredProcedure

  7. Making a connection between Project and SQL Database

    Open the Web.conifig file, one that is not present in the registration folder.

    Replace the code with the following code.

    Code:

    1. <configuration>  
    2.      <connectionStrings>  
    3.          <add name="jsb_ConnectionString" connectionString="data source=.; database=mysamle; user id=sa; password=Password$2"/>  
    4.      </connectionStrings>  
    5.  <system.web>  
    6.      <compilation debug="true" targetFramework="4.0" />  
    7.      <authentication mode="Forms">  
    8.          <forms loginUrl="Login.aspx" defaultUrl="Welcome.aspx">  
    9.          <credentials passwordFormat="Clear">  
    10.          </credentials>  
    11.      </forms>  
    12.      </authentication>  
    13.      <authorization>  
    14.          <deny users="?"/>  
    15.      </authorization>  
    16.      </system.web>  
    17.  </configuration>  
    Now open the Register.aspx.cs page and add the following namespaces.

    Code:
    1. using System.Configuration;  
    2. using System.Data.SqlClient;  
    3. using System.Data;  
    4. using System.Web.Security;  
    In between of bttn_Register_Click add the following code.

    Code:
    1. protected void btn_Register_Click(object sender, EventArgs e)  
    2.  {  
    3.      if (Page.IsValid)  
    4.      {  
    5.          string CS = ConfigurationManager.ConnectionStrings["jsb_ConnectionString"].ConnectionString;  
    6.          using (SqlConnection con = new SqlConnection(CS))  
    7.          {      
    8.              SqlCommand cmd = new SqlCommand("spRegisterUser", con);  
    9.              cmd.CommandType = CommandType.StoredProcedure;  
    10.    
    11.              string EncriptedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(tb_password.Text, "SHA1"); //  
    12.    
    13.              SqlParameter username = new SqlParameter("@UserName", tb_UserName.Text);  
    14.              SqlParameter password = new SqlParameter("@Password", EncriptedPassword); //tb_password.Text  
    15.              SqlParameter email = new SqlParameter("@Email", tb_Email.Text);  
    16.    
    17.              cmd.Parameters.Add(username);  
    18.              cmd.Parameters.Add(password);  
    19.              cmd.Parameters.Add(email);  
    20.    
    21.              con.Open();  
    22.    
    23.              int ReturnCode = (int)cmd.ExecuteScalar();  
    24.              if (ReturnCode == -1)  
    25.              {  
    26.                  lbl_Message.Text = "User Name already in use, please choose another user name";  
    27.              }  
    28.              else  
    29.              {  
    30.                  Response.Redirect("~/Login.aspx");  
    31.              }  
    32.          }  
    33.      }  
    34.  }  
    Run the project and click on “Click here to register”.

    LoginPageThree

    Do a registration as in the following:

    RegistrationThree
    Now the user is registered and will be directed to the Login Page, where only a valid user can login.

    LoginPageFour

    WelcomePageThree

    The following shows the credentials of user “jsb” in the database.

    DatabaseCredentials

    Now, If we want to store an encrypted password in the database then we will do it as in the following. Open the Register.aspx page and edit the code to the following.

    Code:
    1. string EncriptedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(tb_password.Text, "SHA1"); //  
    2.  SqlParameter username = new SqlParameter("@UserName", tb_UserName.Text);  
    3.  SqlParameter password = new SqlParameter("@Password", EncriptedPassword); //tb_password.Text  
    4.  SqlParameter email = new SqlParameter("@Email", tb_Email.Text);  
    Register again:

    RegistrationpageFour
    Check again the credentials of the user “encrypt” in the database.

    LastCheckCredentials

     

I hope, you enjoyed.