articles

Home / DeveloperSection / Articles / Login Form in ASP.Net

Login Form in ASP.Net

Anonymous User 17003 21-Jan-2011

Login Form in ASP.Net

Design View of Login Form

Login form of a designing include a login page where user provides their credential (as shown above). After successful login user will be redirected to sign out page which will be displayed after sign in.

Design Source for Login Page
<body style="height: 452px">
<form id="form1" runat="server">
<asp:Login ID="Login1" runat="server" BackColor="#F7F6F3" BorderColor="#E6E2D8"
BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"
Font-Size="Large" ForeColor="#333333" onauthenticate="Login1_Authenticate"
style="margin-left: 389px; margin-top: 141px">
<InstructionTextStyle Font-Italic="True" ForeColor="Black" />
<LoginButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid"
BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284775" />
<TextBoxStyle Font-Size="0.8em" />
<TitleTextStyle BackColor="#5D7B9D" Font-Bold="True" Font-Size="0.9em"
ForeColor="White" />
</asp:Login>
</form>
Screen shot of the above source

Login Form in ASP.Net

ASP.NET code for login page(LoginPage.aspx.cs)
protected void  Login1_Authenticate(objectsender, AuthenticateEventArgse)
    {
//This condition check that the user who wants to login as administrator or //superadministrator.With the help of substring we check whether user is //administrator or super administrator.
        if (Login1.UserName.Substring(0, 1).Equals("A"))
        {
            //Code to check details of administrator
//if user is administrator then checkAdminDetails() method is called which returns a
//Boolean value that is either true or false.true value represents user id or //password is correct and false value represents user id and password is incorrect.
            if (checkAdminDetails(Login1.UserName, Login1.Password))
            {
//If user login successful then count value should be zero.
                count =0;
                //create a session variable which store userName
                //create a session variable which store login status.
                createUserName();
                Response.Redirect("SuperAdministrator/UserPage.aspx");
            }
            else
            {
//if login attempt is unsuccessful then we increment the value of count.The maximum
//attempt for login is 3
                count++;
                if (count>3)
                {
//if login attempt is greater than 3 then a message is displayed and after displaying
//message browser should be close.
                    Response.Write("<script>alert(''Unauthorized User.Access Is Aborted.');</script>");
//code for closing the browser.
                    Response.Write("<script>window.close()</script>");
                }
                else
                {
//Other wise a message displayed.Invalid user id or password
                    Response.Write("<script>alert('Invalid User Id Or Password.');</script>");
                }
            }
        }
        else
            if (Login1.UserName.Substring(0, 1).Equals("S"))
            {
                //code to check details of super administrator.
                if (checkSuperAdmin(Login1.UserName, Login1.Password))
                {
                    count =0;
                    //create a session variable which store user name
                    //create a session variable which store login status.
                    createUserName();
                    Response.Redirect("SuperAdministrator/Admin.aspx");
                }
                else
                {
//if login attempt is unsuccessful then we increment the value of count.The maximum
//attempt for login is
                    count++;
                    if (count>3)
                    {
                        Response.Write("<script>alert('Unauthorized User.Access Is Aborted.')</script>");
//code for closing the browser
                        Response.Write("<script>window.close()</script>");
                    }
                    else
                    {
//Other wise a message displayed.Invalid user id or password
                        Response.Write("<script>alert('Invalid User Id Or Password.');</script>");
                    }
                }
            }
            else
            {
                Response.Write("<script>alert('Login Id Does Not Exists.')</script>");
            }
    }
 
//count is an static variable which is shared by all page objects which is created by
//server.
staticintcount=0;
 
 
//createUserName() method is used to store the name of the user is //Session[“userName”] variable.If Session[“userName”] variable contains null then it //means user is not login and he is redirected to login page automatically
publicvoid createUserName()
    {
        if (Session["userName"] == null)
        {
            Session["userName"] =Login1.UserName;
       }
    }
 
//checkAdminDetails(string userId,string userPassword) is a method which is used to //check administrator creadentials
publicbool checkAdminDetails(stringuserId, stringuserPassword)
    {
        boolstatus=false;
//A SqlConnection object is created.Connection String is stored in web.config file //and which is retrived with the help of ConfigurationManager class.
        SqlConnectioncon=new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
//Connection with the appropriate server is opened.
        con.Open();
//A SqlCommand object is created.When we create SqlCommand object the its constructor //takes two parameter.First parameter represents the query or procedure which needs //to be executed while second parameters represent connection object
        SqlCommandcmd=new SqlCommand("checkLoginId", con);
//Here we tell the type of query that it is text or stored procedure.
        cmd.CommandType=CommandType.StoredProcedure;
//Here we created parametrized procedure that’s why we have to add parameters.When we
//create object of SqlParameter class its constructor takes two parameter first
//parameter represents name of the parameter and second parameters represent the //value of the parameter.
        cmd.Parameters.Add(newSqlParameter("@loginId", userId));
        cmd.Parameters.Add(newSqlParameter("@password", userPassword));
//Here we create the object of SqlDataReader object which contains result sets of the //query
        SqlDataReaderdr=cmd.ExecuteReader();
//if SqlDataReader object contains any row then status should be true.means user is //authenticated otherwise false.
        if (dr.Read())
        {
            status=true;
        }
        else
        {
            status=false;
        }
        returnstatus;
    }
//checkSuperAdmin(string username,string userPassword) is used to validate the //creadential of super administrator.It returns a Boolean value that is either true //or false.If it returns true then user is authenticated otherwise user is not //authenticated
publicbool checkSuperAdmin(stringuserName, stringuserPassword)
    {
        boolstatus=false;
        if (userName.Equals("S0001") &&userPassword.Equals("admin"))
        {
            status=true;
        }
        else
        {
            status=false;
        }
        returnstatus;
    }

Once the user is login we have to design a redirected page.

Screen Shot of Redirected Page

Login Form in ASP.Net

If you want that after log out user can not retrieve pages from browser cache until he logged in the write down the following code at the end of Page_PreInit() event.

protectedvoidPage_PreInit(objectsender, EventArgse)
    {
        Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetNoStore();
    }

 

When user press the log out button then all the session information is cleared. And he returns back to the loginPage.

Sorce Code For Log Out
//when user click the log out button then Session[“userName”] variable contains null //value which means user is log out.And we finnaly call the loginPage again.
protectedvoidbtnLogOut_Click(objectsender, EventArgse)
    {
        Session["userName"] =null;
        Response.Redirect("../LoginPage.aspx");
    }




Updated 24-Oct-2019
I am a content writter !

Leave Comment

Comments

Liked By