How to implement Form Based authentication in asp.net appplication

By
Form based authentication class resides within "System.web.security"Namespace .  There are two technique which  used to  authenticate the user manually by following ways.
  1. By the hard code value
  2. By the web.config file
     1.) By the hard code value:- In this user can verify (authenticate) the web form (login.aspx) by specifying the user name and password from hard code value.
    2.) By web.config file:-In this user can authenticate (verify ) the web form    (login.aspx page) by specifying the user name and password from web.config file.

Note:- We can authenticate the user name and password from database also.
Where we can use this Authentication:-
Suppose you have limited employee in your organization(ex.200 employee).if you want to host your  asp.net website on server to provide the relevant information to your employee. if you want ,only company 's member can access the asp.net website then you will have to generate user name and password manually and save in web.config file or in hard code values.If you want  to share secure information on your asp.net website so that only company's members can access them,then you will have to provide user name and password to each employee which you have mentioned in web.config file or hard code values.If any employee want to see the information send by the manager of company then they will have to verify your user name and password which is provide by the organization(manager). When any employee open the website then login page (login.aspx)  will be opened first, after authenticate the login page with user name and password employee will be redirected to home page (main page) of the website.After access the application you have to Logout .Other wise any anonymous user can login as your name with the help of browser cookie(persistence or Non persistence) data.It can be more harmful for an organization(company). 
There are some attribute and element which we can  use in web.config file (under authentication and authorization section).

  1. name:-It is a optional attribute.It specifies the HTTP Cookie to use for authentication.If you are running multiple application on server then you will be required a unique cookie name in each web.config file for each application. ASPXAUTH is a default name where cookie data is stored.
  2. loginUrl :- It is a optional attribute that specifies the URL to which the request is redirected for logon.In this application ,i have set login.aspx page for logon. If no valid cookie  is found for authentication then it will automatically redirected to login.aspx page.
  3. defaultUrl :- It is a optional attribute .It defines the default URL that is used for redirection after authentication.I have already set defaultUrl = "home.aspx" in my application.
  4. Protection:- It specifies the type of encryption if any to use for cookie.This option usages the configuration data validation algorithm such as DES and Triple DES If it is available.
  5. Path:- It specifies the path cookies that are used by the application.Most of  Browsers at this time are case sensitive.If there is a path case mismatch then it don't  send cookies back to the application. 
  6. requiredSSL :- It specifies whether an SSL connection is required  to transmit  the authentication cookie.In my application ,i have used requiredSSL ="false".
  7. Timeout:- It is a time in minute after which the cookie of browser will be expired.By default it is 30 minute.
  8. slidingExpiration:- It specifies whether sliding Expiration is enabled,sliding Expiration resets the active authentication time for a cookie to expire on each request during single session.
  9. credentials:- It allow user name and password credentials within configuration file.We can easily create custom user name and password scheme to use an  external source for authentication of web page like database.
  10. Authentication:- It is a parent element of web.config file.It is used to identify the users who view an asp.net application.
There are some steps to implement this concepts on asp.net application.
Step 1:- First open your visual studio-->File -->New -->Website-->Select asp.net Empty website -->OK-->Open solution Explorer -->Add a Web Form (login.aspx)-->Drag and drop Label ,Text Box and Button control from the tool Box as shown below:-

logon form

Step 2:- Now add another web form  (home.aspx) in your project-->Drag and drop Button and Label control as shown below:-

home_form

Step 3:- Now open web.config file -->writes the following codes as given below:-
<configuration>
 <system.web>
       <authentication mode="Forms">
        <forms  name=".ASPXAUTH"
          loginUrl="login.aspx" 
          defaultUrl="home.aspx"  
          protection="All" 
          path="/"
          requireSSL="false"
          timeout="20"
          slidingExpiration="true ">   
          <credentials passwordFormat="Clear">
            <!--<credentials passwordFormat="SHA1">-->
            <!--<credentials passwordFormat="MD5">-->
            <user name="ram" password="ram123"/>
            <user name="shayam" password="shayam123"/>
            <user name="neha" password="neha123"/>
          </credentials>
          </forms>  
      </authentication>
      <authorization>
        <deny users="?"/>
        <allow users="*"/>
      </authorization>
      <compilation debug="true"/>
  </system.web>
</configuration>

Note:- Here, i have created some user name and password manually in web.config file.Only these users can be able to authenticate the login.aspx page.
Step 4:- Open login.aspx page --> Write the following c# codes for each button codes(login.aspx.cs ) as given below:-

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["id"] = TextBox1.Text;
    }
    
    protected void Button1_Click(object sender, EventArgs e)
    {
        bool validformlogin = false;
        validformlogin = Authenticate_user(TextBox1.Text.Trim(), TextBox2.Text.Trim());

        if (validformlogin)
        {
            FormsAuthentication.RedirectFromLoginPage(TextBox1.Text.Trim(), false);
        }
        else
        {
            Response.Write("invalid login ..try again");
        }
    }

    private bool Authenticate_user(string user_name, string password)
    {
        if (user_name == "admin" && password == "admin123")
        {
            return true;
        }
        else if(user_name == "neha" && password == "neha123")
            {
            return true;
            }
        else if (user_name == "sanjay" && password == "sanjay123")
        {
            return true;
        }
        else
        {
            return false;
        }

    }

    protected void Button2_Click1(object sender, EventArgs e)
    {
        if (FormsAuthentication.Authenticate(TextBox1.Text, TextBox2.Text))
        {
            FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false);
        }
        else
        {
            Response.Write("invalid user ...try again");
        }
    }
}

Description:- In button 1 and button 2 clicks,i have written a common function which is given below:-
  • RedirectLoginPage Function:-> This function takes two parameter, one is for user name for whom cookie is created and second one is Boolean value to specify whether cookie is persistence or Non Persistence. This function checks the URL of login page,if it return the URL specify in web.config then user will be redirected to that web page and it checks web.config file for defaultUrl .It specify, user is redired to that web page but it not specify,user will be redirected to defaultUrl page. 
  • Password Format Attribute:-> This attribute is used in format ,in which, password value is given in web.config file.If this attribute  value is clear ,it means  password value is store in plane text format.If this attribute  value is  in MD5 or SHA1 ,it means Password is stored in encrypted form By using MD5 or SHA1 . To set the encrypted values of some plane text we can call "HashPasswordForStoringIn ConfigFile" class.it  takes two parameter
              1.) value for the text which we want to encrypt
              2.) Value for name of algorithm 
Example:- If you are using password format MD5 or SH1 then you can use below c# codes:-
protected void Page_Load(object sender, EventArgs e)
    {
 Response.Write(FormsAuthentication.HashPasswordForStoringInConfigFile("filename", "SHA1"));
    }
  • If there are some resources which have to access by all the users then we can specify that tag by using location tag in web.config file.I have already used location tag in windows authentication tutorials.
Note:- Here, Codes on first button click ,we can authenticate only those user which satisfied the if and else if conditions.
Step 5:- Now open home.aspx page -->write the c# codes in home.aspx.cs file as given below:-
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class home : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            Label1.Text = Session["id"].ToString();
        }
        catch
        {
            Response.Redirect("login.aspx");
        }
       
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Session.RemoveAll();
        Response.Redirect("login.aspx");
    }
}

Step 6:- Now Run the application (press F5)--> Filled the required field values (user name and password) for hard code value authentication-->press Login through hard code button.


login_output

Step 7:- Now Run the application again --> Verify (authenticate) the web page(login.aspx ) by user name and password fields from web.config file as shown below:-


output

Step 8:- If you don't enter correct details (user name or password ) which specify in hard code or web.config file the it will give following error as shown below:


error _page

Step 9:- If you save the password in browser cookie -->then you can login without user name and password.But it is harmful ,if any other user access your computer.-->so press Logout Button before exit the application.

Note:- In coming tutorial will put full security features in existing login control Using Administrative Tool property of  visual studio 2010.
For More.....
  1. How to connect any database through OleDb connection
  2. How to use different connection string in asp.net application
  3. How to edit delete insert update and print operation in Data List control
  4. Data mining in asp.net
  5. Session state in asp.net
  6. Joins in Sql server 2008
  7. How to send mail from asp.net application free
  8. Web Form control  in asp.net
  9. How to host asp.net website on server free
  10. Stored procedure in sql server
  11. Take print receipt in windows forms application
  12. Data Integrity in sql server 2008
Download whole attached file from below
              Download

4 comments:

  1. thanks , you really saved my time ..

    ReplyDelete
  2. Having no Master page currently but facing this problem "A page can have only one server-side Form tag." after clicking "Hard code" button.

    Any help?

    ReplyDelete
  3. Dear Needing, .NET is a programming framework created by Microsoft that developers can use to create applications more easily. As commenter dwroth aptly put it, "a framework is just a bunch of code that the programmer can call without having to write it explicitly." In a perfect world, you wouldn't need .NET Framework

    ReplyDelete
  4. Thanks...its very helpful..

    ReplyDelete

Powered by Blogger.