Reader Level:
ARTICLE

Password Encryption For Forms Authentication in ASP.Net

Posted by Pankaj Lohani Articles | ASP.NET Controls December 16, 2013
This article explains Forms Authentication and how to generate the encrypted password for Forms Authentication.
  • 1
  • 0
  • 8565

EIntroduction

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

Forms Authenctication

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.

<authentication mode="Forms">

      <forms name="GenratePwd.aspx">

        <credentials passwordFormat="SHA1">

          <user name="Admin" password="A48911A9D19A1882B35EB2F22FB75CA32307E27A"/>

        </credentials>

      </forms>

    </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.

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

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

 public GenratePwd()

    {

        //Pankaj is the password for the admin that is encrypted by HasPasswordForStoringInConfigFile method.

        string ns = FormsAuthentication.HashPasswordForStoringInConfigFile("Pankaj""SHA1");

        //Password is encrypted in a text file P.txt

        StreamWriter s = File.CreateText("C:\\Pankaj\\P.txt");

        s.WriteLine(ns);

        s.Close();

    }

 

When you will compile this programme it will genrate 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

create database UserLoginDetails

use UserLoginDetails

create table UserLogin

(

UserName nvarchar(max),

Password nvarchar(max)

)

 

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

 

insert into UserLogin values('pankaj.lohani@gmail.com','1234')

insert into UserLogin values('Nimit.Joshi@gmail.com','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 :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GenratePwd.aspx.cs" Inherits="GenratePwd" %>

 

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <table border="0">

    <tr>

    <td>

    Enter User Name

    </td>

    <td>:</td>

    <td>

    <asp:TextBox ID="txtuser" runat="server"></asp:TextBox>

    </td>

    </tr>

        <tr>

    <td>

    Enter Password

    </td>

    <td>:</td>

    <td>

    <asp:TextBox ID="txtpwd" runat="server" TextMode="Password"></asp:TextBox>

    </td>

    </tr>

    <tr>

    <td colspan="2">

    <asp:Button ID="btnsumit" runat="server" Text="Submit" OnClick="btnsumit_Click"/>

    </td>

    </tr>

    </table>

    </div>

    </form>

</body>

</html>

 

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

 

<authentication mode="Forms">

      <forms name="GenratePwd.aspx">

        <credentials passwordFormat="SHA1">

          <user name="Admin" password="A48911A9D19A1882B35EB2F22FB75CA32307E27A"/>

        </credentials>

      </forms>

    </authentication>

<connectionStrings>

 <add name="dbconnection" connectionString="Data Source=; Initial Catalog=UserLoginDetails; 

User=abc; Password=****" providerName="SqlClient"/>

</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 :

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.IO;

using System.Web.Security;

using System.Security.Cryptography;

using System.Data;

using System.Data.SqlClient;

using System.Web.UI;

using System.Configuration;

using System.Web.UI.WebControls;

 

public partial class GenratePwd : System.Web.UI.Page

{

    string conString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    public GenratePwd()

    {

        //Pankaj is the password for the admin that is encrypted by SHA1 algorithm

        string ns = FormsAuthentication.HashPasswordForStoringInConfigFile("MyPassoword""SHA1");

        //Password is encrypted in a text file P.txt

        StreamWriter s = File.CreateText("C:\\Pankaj\\P.txt");

        s.WriteLine(ns);

        s.Close();

    }

    protected void btnsumit_Click(object sender, EventArgs e)

    {

        string un = txtuser.Text;

        Session["Username"] = txtuser.Text;

        string pwd = txtpwd.Text;

        if(FormsAuthentication.Authenticate(un,pwd))

        {

            Response.Redirect("AdminAccount.aspx");

        }

        else

        {

            SqlConnection con = new SqlConnection(conString);

            SqlCommand cmd = new SqlCommand("Select UserName, Password from UserLogin Where UserName='"+un+"' and Password='"+pwd+"'",con);

            con.Open();

            SqlDataReader rdr = cmd.ExecuteReader();

            bool b = rdr.Read();

            if (b == true)

            {

                Response.Redirect("UserAccount.aspx");

                con.Close();

            }

            else

            {

                Page.RegisterStartupScript("Alert Message",

         "<script language='javascript'>alert('username and password is incorrect try again');</script>");

                return;

            }

        }

    }

}

 

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.

COMMENT USING

Trending up