Thursday 31 March 2011

Form Authentication(Big Security) in ASP.Net


Introduction: In this article, i will  explain about the tight security of the asp.net, i mean form authentication . This is very powerful security of the asp.net. Now days every client demand hard security. Because there is very importation information stores in the  databases of the every website. If the data of these website will be stolen by the hackers , it can be create a big problem. So we need security for the data that is available in the website.  Asp.NET provide us a big security named as Form Authentication” . Here i will explain how we can create this security in asp.net.

Implementation : First create a website in asp.net. Then Create three folders inside the root directory.  Below i am  giving the name of these folders.
1.    Admin
2.    Client
3.    Director
Then create one-one .aspx pages inside of every folder named first_admin.aspx,first_client.aspx and first_director respectively inside the folders. Then create a table inside the sel server named tb_login. Below i am giving the column name and the datatype of every column.
----------------------------------------------------------------------------------------------------------------
Columnname                         datatype
Id                                          bigint(autogenerate property - yes)
Username                              varchar(50)
Password                              varchar(50)
Role                                      vartchar(50)  
-----------------------------------------------------------------------------------------------------------------   
Enter the three rows inside this table as data.
Id                            username                               password                                  Role
 1                            raman                                    raman                                        admin
2                             vimal                                      vimal                                         client
3                             vishal                                     vishal                                         director
--------------------------------------------------------------------------------------------------------------
Raman can access only “Admin” folder and vimal can access only “Client” folder and vishal can access only “Director” folder.
Then create a login.aspx page inside the root directory. In the login page there will be two textboxes and a button and a label named respectively user_txt,pwd_txt, login_btn and lbl_msg.
Code of Login.aspx      
<table >
            <tr>
                <td >
                    Username:</td>
                <td>
                   
                    <asp:TextBox ID="user_txt" runat="server"></asp:TextBox>
;<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                        ControlToValidate="user_txt" ErrorMessage="Required" ValidationGroup="a"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td >
Password:</td>
                <td>
                   
                    <asp:TextBox ID="pwd_txt" runat="server" TextMode="Password"></asp:TextBox>
;<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
                        ControlToValidate="pwd_txt" ErrorMessage="Required" ValidationGroup="a"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td >
;</td>
                <td>
                    </td>
            </tr>
            <tr>
                <td>
                    </td>
                <td>
                    ;
                    <asp:Button ID="login_btn" runat="server" onclick="login_btn_Click"
                        Text="Login" ValidationGroup="a" Width="122px" />
</td>
            </tr>
               
            </table>     

Code of login.aspx.cs page
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class login : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection();
    SqlDataAdapter adp;
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void login_btn_Click(object sender, EventArgs e)
    {
        con.ConnectionString = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
        con.Open();
//   here with the help of this sql query i am matching the username and password of //the user.

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "select  username,password, role from tb_Login where username COLLATE Latin1_general_CS_AS=@ username and   password=@ password ";

        cmd.Connection = con;
//   here i am passing the parameter of username and  password
        cmd.Parameters.Add("@username", SqlDbType.VarChar, 50).Value = user_txt.Text;
        cmd.Parameters.Add("@password", SqlDbType.VarChar, 50).Value = pwd_txt.Text;
        SqlDataReader dr = cmd.ExecuteReader();
//   here i am using hasrows to check the correct user. If the username and the passwor //of the user will be mathed with the database then it will be go to the checkuser.aspx //page otherwise it prints the message wrongusername or password    
  if (dr.HasRows)
        {
            dr.Read();
//   here i am creating a formauthentication ticket that will be use in   the whole //application. This is the main part of the formauthentication security, inside dr[2] //there is  a role of the user
            FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, user_txt.Text, DateTime.Now, DateTime.Now.AddHours(3), false, dr[2].ToString(), FormsAuthentication.FormsCookiePath);
//   here i am enctypt the ticket. With the encryption  of this ticket it will encrypt the //username
            String st = FormsAuthentication.Encrypt(tkt);
//   here i am creat a cookie that will we used inside the whole application
                        HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, st);
            Response.Cookies.Add(ck);

            Response.Redirect("checkuser.aspx");
           
        }
        else
        {
            Response.Write("wrong user/pwd");
        }
    }  

Then create a another page named checkuser.aspx. below i am giving the code for this page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class checkuser : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
//   here iam explainnig that if the role of the user that will be login is admin ,he will /be go to the admin folder, if the role will we client then it will be go to the client //folder , if the role will be director then it will be go to the director folder

        if (User.IsInRole("admin"))
        {
            Response.Redirect("admin/first_admin.aspx");
        }
        else if (User.IsInRole("client"))
        {

            Response.Redirect("client / first_client.aspx");
        }
        else if (User.IsInRole("director"))
        {

            Response.Redirect("director / first_ director.aspx");
        }

        else
        {
            Response.Redirect("login.aspx");

        }            
Code for webconfig file:

In place of <authentication mode="window"/> write the below code in the webconfig.

<authentication mode="Forms">
      <forms name="abc" loginUrl="login.aspx"></forms>
    </authentication>
After </system.web>  write this code inside the webconfig accoring to ur requirement. I mean explain here your folders and the roles that you are giving to the user

</system.web>


  <location path="Admin">
    <system.web>
      <authorization>
        <allow roles="admin"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path=”client”>
    <system.web>
      <authorization>
        <allow roles="client"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
<location path=”director”>
    <system.web>
      <authorization>
        <allow roles="director"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

Now add global.asax file  in your root directory. and write the below code inside this file..
<%@ Application Language="C#" %>

<%@ Import Namespace="System.Security.Principal"%>


<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
   
    void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown

    }
       
    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started

    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.

    }

    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            FormsIdentity fi;
            fi = (FormsIdentity)(User.Identity);
            FormsAuthenticationTicket k;
            k = fi.Ticket;
            String ud = k.UserData;
            String[] ar = ud.Split('|');
            HttpContext.Current.User = new GenericPrincipal(fi, ar);           
        }
    }
</script>


Conclusion: In this article you have learned about the comple form authentication security in the asp.net. once again to all asp.net developer i wnt to say rhat this security is very important, if you want to secure your data of the database. This is very important security in the asp.net

                                    

5 comments:

  1. Good One !! It Helped Me To understand the
    Concept of
    "Global.asax" file.

    Thanks A Ton, "PAAJI"

    ReplyDelete
  2. when i enter user name:ramana password:ramana still its in login page its not redirection to admin page
    can you please help me on this

    ReplyDelete
    Replies
    1. Please dugbug the code. And use break point. There is definatly any mistake from ur side.
      Regards
      Using Asp.net

      Delete