Password Encryption For Forms Authentication in ASP.Net

Introduction

This article explains Forms Authentication and how to generate the encrypted password for Forms Authentication.

Forms Authentication

With Forms Authentication you create a login page containing the credentials from the user and that includes code to authenticate the credentials. Forms Authentication provides you with a way to handle authentication using your own custom logic. ASP.Net leverages it's framework to support cookies and establishes the security context for each web request; this is called a Form Authentication.

  1. <authentication mode="Forms">  
  2.       <forms name="GenratePwd.aspx">  
  3.         <credentials passwordFormat="SHA1">  
  4.           <user name="Admin" password="A48911A9D19A1882B35EB2F22FB75CA32307E27A"/>  
  5.         </credentials>  
  6.       </forms>  
  7. </authentication> 

In a <authentication> tag we validate the username and password, here the user tag contains the two attributes "name" and "password". In a password attribute you need to copy the encrypted  password from the text file and paste it here. One <User> tag stores only one username and password. If you want to use multiple usernames and passwords then you need to use another user tag.

HashPassowordForStoringInConfigFile Method

The "HashPasswordForStoringInConfigFile" method creates a hashed password value that can be used when storing Forms Authentication credentials in the configuration file. You may want to store passwords securely in a Web.config file. You can use the "FormsAuthentication" class utility function named "HashPasswordForStoringInConfigFile" to encrypt the password before you save it in a configuration file.

  1. string ns = FormsAuthentication.HashPasswordForStoringInConfigFile("Your Password""SHA1");  

The password that is encrypted by the "FormsAuthentication.HashPasswordForStoringConfigFile" method using the Secure Hash Algorithm (SHA1).

  1. public GenratePwd()  
  2. {  
  3.     //Pankaj is the password for the admin that is encrypted by HasPasswordForStoringInConfigFile method.  
  4.     string ns = FormsAuthentication.HashPasswordForStoringInConfigFile("Pankaj""SHA1");  
  5.     //Password is encrypted in a text file P.txt  
  6.     StreamWriter s = File.CreateText("C:\\Pankaj\\P.txt");  
  7.     s.WriteLine(ns);  
  8.     s.Close();  
  9. } 

When you will compile this program it will generate an encrypted code in a text file. Just specify the path where you want to save this file then copy this code and paste in the password attribute. Let's see that as in the following figure.

EncryptPassword

Now  I will show you how to generate the password for the Admin user in Forms Authentication. Use the following procedure to do that.

Create Database and Table in SQL-SERVER

  1. create database UserLoginDetails  
  2. use UserLoginDetails  
  3. create table UserLogin  
  4. (  
  5. UserName nvarchar(max),  
  6. Password nvarchar(max)  
  7. ) 

Use the following procedure to insert the values in a table:

  1. insert into UserLogin values('[email protected]','1234')  
  2. insert into UserLogin values('[email protected]','123456')

Step 1

Open Visual Studio then select "Create New Website" --> "ASP.NET Web Site".

NewWebsite

Step 2

Now go to the Solution Explorer to the right side of the application and use the procedure in the following figure.

AddNewItem

Step 3

Add a new Web form in the empty web application as in the following figure.

NewWebForm

Use the following code in the "GenratePwd.aspx" page:

Step 4

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GenratePwd.aspx.cs" Inherits="GenratePwd" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.     <div>  
  10.     <table border="0">  
  11.     <tr>  
  12.     <td>  
  13.     Enter User Name  
  14.     </td>  
  15.     <td>:</td>  
  16.     <td>  
  17.     <asp:TextBox ID="txtuser" runat="server"></asp:TextBox>  
  18.     </td>  
  19.     </tr>  
  20.         <tr>  
  21.     <td>  
  22.     Enter Password  
  23.     </td>  
  24.     <td>:</td>  
  25.     <td>  
  26.     <asp:TextBox ID="txtpwd" runat="server" TextMode="Password"></asp:TextBox>  
  27.     </td>  
  28.     </tr>  
  29.     <tr>  
  30.     <td colspan="2">  
  31.     <asp:Button ID="btnsumit" runat="server" Text="Submit" OnClick="btnsumit_Click"/>  
  32.     </td>  
  33.     </tr>  
  34.     </table>  
  35.     </div>  
  36.     </form>  
  37. </body>  
  38. </html> 

Add the ConnectionString and Admin Credentials in the Web.config file as in the following:

  1. <authentication mode="Forms">  
  2.       <forms name="GenratePwd.aspx">  
  3.         <credentials passwordFormat="SHA1">  
  4.           <user name="Admin" password="A48911A9D19A1882B35EB2F22FB75CA32307E27A"/>  
  5.         </credentials>  
  6.       </forms>  
  7.     </authentication>  
  8. <connectionStrings>  
  9.  <add name="dbconnection" connectionString="Data Source=; Initial Catalog=UserLoginDetails;   
  10. User=abc; Password=****" providerName="SqlClient"/>  
  11. </connectionStrings> 

You configure Forms Authentication using the "authentication" configuration element. In a Web.config file we specify a login page, "GenratePwd.aspx", and authenticate the credentials for the Authenticate method. The password has been encrypted using the "HashPasswordForStoringInConfigFile" method.

Use the following code in "GenratePwd.aspx.cs":

Step 5

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.IO;  
  6. using System.Web.Security;  
  7. using System.Security.Cryptography;  
  8. using System.Data;  
  9. using System.Data.SqlClient;  
  10. using System.Web.UI;  
  11. using System.Configuration;  
  12. using System.Web.UI.WebControls;  
  13. public partial class GenratePwd : System.Web.UI.Page  
  14. {  
  15.     string conString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;  
  16.     protected void Page_Load(object sender, EventArgs e)  
  17.     {  
  18.     }  
  19.     public GenratePwd()  
  20.     {  
  21.         //Pankaj is the password for the admin that is encrypted by SHA1 algorithm  
  22.         string ns = FormsAuthentication.HashPasswordForStoringInConfigFile("MyPassoword""SHA1");  
  23.         //Password is encrypted in a text file P.txt  
  24.         StreamWriter s = File.CreateText("C:\\Pankaj\\P.txt");  
  25.         s.WriteLine(ns);  
  26.         s.Close();  
  27.     }  
  28.     protected void btnsumit_Click(object sender, EventArgs e)  
  29.     {  
  30.         string un = txtuser.Text;  
  31.         Session["Username"] = txtuser.Text;  
  32.         string pwd = txtpwd.Text;  
  33.         if(FormsAuthentication.Authenticate(un,pwd))  
  34.         {  
  35.             Response.Redirect("AdminAccount.aspx");  
  36.         }  
  37.         else  
  38.         {  
  39.             SqlConnection con = new SqlConnection(conString);  
  40.             SqlCommand cmd = new SqlCommand("Select UserName, Password from UserLogin Where UserName='"+un+"' and Password='"+pwd+"'",con);  
  41.             con.Open();  
  42.             SqlDataReader rdr = cmd.ExecuteReader();  
  43.             bool b = rdr.Read();  
  44.             if (b == true)  
  45.             {  
  46.                 Response.Redirect("UserAccount.aspx");  
  47.                 con.Close();  
  48.             }  
  49.             else  
  50.             {  
  51.                 Page.RegisterStartupScript("Alert Message",  
  52.          "<script language='javascript'>alert('username and password is incorrect try again');</script>");  
  53.                 return;  
  54.             }  
  55.         }  
  56.     }  
  57. } 

if(FormsAuthentication.Authenticate(un,pwd))// Authenticate( ) takes two argument.s It validates a username and password against credentials stored in a Web.config file for an application. The "Authenticate" method is to be used with the "FormsAuthentication" class.

Step 6

Debug the application by pressing F5 to execute the Web form. After debugging the application the output will be as in the following figure:

Debug

Step 7

Enter the Admin Id and password. These credentials are checked from the Web.config file as in the following figure:

AdminAccount

Step 8

The Welcome page for as in the following:AdminAccount is as in the following figure:

WelcomeAdmin

Step 9

Enter the User Id and Password . These credentials are cheked from the database as in the following figure.

UserLogin

Step 10

The Welcome Page for User Login is as in the following figure.

WelcomeUser

Step 11

Page Validate if Admin/User Id and Password is not found as in the following figure.

PageValidate

Summary

This article has shown how to generate an encrypted password for Forms Authentication in ASP.Net.


Similar Articles