Home / ASP.NET Wiki / State Management / Cookies / Login through cookies

Login through cookies

 Rate It (9)

Different forums are filled with the questions regarding how to manually implement cookies for login or in other words how to implement "Remeber me" option.

Following is the code that will give the idea of how to achieve this task.

Controls used
1. TextBox, ID = TbUserName
2. TextBox, ID = TbPassword
3. CheckBox, ID = CbRememberMe
4. Button, ID = BtLogin
5. LinkButton, ID = lbSignout

------------------If you are using VB.Net-------------------------

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            'Check if the browser support cookies
            If Request.Browser.Cookies Then
               'Check if the cookies with name PBLOGIN exist on user's machine
                If Request.Cookies("PBLOGIN") IsNot Nothing Then
                    'Pass the user name and password to the VerifyLogin method
                    Me.VerifyLogin(Request.Cookies("PBLOGIN")("UNAME").ToString(), Request.Cookies("PBLOGIN")("UPASS").ToString())
                End If
            End If
        End If
    End Sub

    Protected Sub BtLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        'check if remember me checkbox is checked on login
        If (Me.CbRememberMe.Checked) Then
            'Check if the browser support cookies
            If (Request.Browser.Cookies) Then
                'Check if the cookie with name PBLOGIN exist on user's machine
                If (Request.Cookies("PBLOGIN") Is Nothing) Then
                    'Create a cookie with expiry of 30 days
                    Response.Cookies("PBLOGIN").Expires = DateTime.Now.AddDays(30)
                    'Write username to the cookie
                    Response.Cookies("PBLOGIN").Item("UNAME") = Me.TbUserName.Text
                    'Write password to the cookie
                    Response.Cookies("PBLOGIN").Item("UPASS") = Me.TbPassword.Text
  'If the cookie already exist then wirte the user name and password on the cookie
                Else
                    Response.Cookies("PBLOGIN").Item("UNAME") = Me.TbUserName.Text
                    Response.Cookies("PBLOGIN").Item("UPASS") = Me.TbPassword.Text
                End If
            End If
        End If

        Me.VerifyLogin(Me.TbUserName.Text, Me.TbPassword.Text)
    End Sub

    Protected Sub VerifyLogin(ByVal UserName As String, ByVal Password As String)
        Try
            'If login credentials are correct
                 'Redirect to the user page
            'else
                 'prompt user for invalid password
            'end if
        Catch ex as System.Exception
            Response.Write(ex.Message)
        End Try
    End Sub

    Protected Sub lbSignout_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbSignout.Click
 'Check iIf the cookies with name PBLOGIN exist on user's machine
        If (Request.Cookies("PBLOGIN") IsNot Nothing) Then
            'Expire the cookie
            Response.Cookies("PBLOGIN").Expires = DateTime.Now.AddDays(-30)
        End If

        'Redirect to the login page
    End Sub
End Class

------------------If you are using C#.Net-------------------------

partial class _Default : System.Web.UI.Page
{
   
    protected void Page_Load(object sender, System.EventArgs e)
    {
        if (!IsPostBack)
        {
            //Check if the browser support cookies
            if (Request.Browser.Cookies)
            {
                //Check if the cookies with name PBLOGIN exist on user's machine
                if (Request.Cookies("PBLOGIN") != null)
                {
                    //Pass the user name and password to the VerifyLogin method
                    this.VerifyLogin(Request.Cookies("PBLOGIN")("UNAME").ToString(), Request.Cookies("PBLOGIN")("UPASS").ToString());
                }
            }
        }
    }
   
    protected void BtLogin_Click(object sender, System.EventArgs e)
    {
        //check if remember me checkbox is checked on login
        if ((this.CbRememberMe.Checked))
        {
            //Check if the browser support cookies
            if ((Request.Browser.Cookies))
            {
                //Check if the cookie with name PBLOGIN exist on user's machine
                if ((Request.Cookies("PBLOGIN") == null))
                {
                    //Create a cookie with expiry of 30 days
                    Response.Cookies("PBLOGIN").Expires = DateTime.Now.AddDays(30);
                    //Write username to the cookie
                    Response.Cookies("PBLOGIN").Item("UNAME") = this.TbUserName.Text;
                    //Write password to the cookie
                    Response.Cookies("PBLOGIN").Item("UPASS") = this.TbPassword.Text;
                }
                //If the cookie already exist then wirte the user name and password on the cookie
                else
                {
                    Response.Cookies("PBLOGIN").Item("UNAME") = this.TbUserName.Text;
                    Response.Cookies("PBLOGIN").Item("UPASS") = this.TbPassword.Text;
                }
            }
        }
       
        this.VerifyLogin(this.TbUserName.Text, this.TbPassword.Text);
    }
   
    protected void VerifyLogin(string UserName, string Password)
    {
        try
        {
             //If login credentials are correct
                  //Redirect to the user page
             //else
                  //prompt user for invalid password
             //end if
        }
        catch (System.Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
   
    protected void lbSignout_Click(object sender, System.EventArgs e)
    {
        //Check iIf the cookies with name PBLOGIN exist on user's machine
        if ((Request.Cookies("PBLOGIN") != null))
        {
            //Expire the cookie
            Response.Cookies("PBLOGIN").Expires = DateTime.Now.AddDays(-30);
        }
       
        //Redirect to the login page
    }

}

Revision number 1, Sunday, March 23, 2008 4:40:19 AM by farazsk11

Comments

It's Not a Good Practice to store the Password in a clear format ! instead it must be encrypted ! because anyone can intercept the cookie and read the user Password... Why Not to Just use the Built In FormsAuthentication , it support the Remember me , just use FormsAuthentication.SetAuthenticationCookie(UserName,True) the second parameter (true) means that the cookie is persisted "Remember the User" .

Hi Anas/All, We have Forms Authentication for our application, we redirect the user to login page once the user is authenticated, iam using the following code to redirect to the login page. FormsAuthentication.RedirectFromLoginPage(username,false) now the problem is once the session is expired it we have some pages inside the folders and once the pages in the folders session is expired it is not redirected to the login page, Instead it is giving as "Internet is unable to display the page". If any body know a solution for this please let me know it will be helpfull.

Hi, I got the solution again i will reiterate the problem what happened is We are using Forms Authentication in our application; we have some issue while integrating with web desktop. We are opening the multiple windows in desktop. If we do any postback from any of the window after session timed out, we are not able to redirect to Login Page. We are getting the IE default page with some error the problem was in web.config setting what happened is .net is treating the postback from any of the window as different application this issue is resolved by providing enableCrossAppRedirects="true"

It is remember when you take password from cookie in textbox which TextMode propert set to "Password" then it will not display, so use txtPWD.Attributes.Add("Value", Request.Cookies("myCookie")("PWD").ToString)

just use an encryption algorithem..

Hi, I am trying to test your example to see how it works, but I'm not getting it. Can you help me by explaining how to test it in visual studio 2008 please.

//i have written something like this after reading your code in vwd 2008 express edition but its not working can you suggest me something please protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Request.Browser.Cookies) { if (Request.Cookies["PBLogin"] != null) { this.VerifyLogIn(Request.Cookies["PBLogin"]["Name"].ToString(), Request.Cookies["PBLogin"]["Passwrd"].ToString()); } } } } protected void imgbtnGo_Click(object sender, ImageClickEventArgs e) { HttpCookie cookie = new HttpCookie("PBLogin"); if (this.cbRemmbrMe.Checked) { if (Request.Browser.Cookies) { if (Request.Cookies["PBLogin"] == null) { cookie.Expires = DateTime.Now.AddMonths(1); cookie["Name"] = tboxName.Text; cookie["Passwrd"] = tboxPasswrd.Text; Response.Cookies.Add(cookie); } else { Response.Cookies["PBLogin"]["Name"] = tboxName.Text; Response.Cookies["PBLogin"]["Passwrd"] = tboxPasswrd.Text; } } } this.VerifyLogIn(this.tboxName.Text, this.tboxPasswrd.Text); } protected void VerifyLogIn(string username, string password) { Session["UserName"] = tboxName.Text; //HttpCookie cookie = new HttpCookie("UserName"); string validateSQL = "select User_Name, Password from Manoranjan_LogIn where User_Name = @User_Name and Password = @Passwrd"; SqlConnection con = new SqlConnection(ConnectionString); SqlCommand cmd = new SqlCommand(validateSQL, con); SqlDataReader rdr; cmd.Parameters.AddWithValue("@User_Name", tboxName.Text); cmd.Parameters.AddWithValue("@Passwrd", tboxPasswrd.Text); try { con.Open(); rdr = cmd.ExecuteReader(); rdr.Read(); //cookie["Name"] = rdr[0].ToString(); //cookie["Passwrd"] = rdr[1].ToString(); //Response.Cookies.Add(cookie); //cookie.Expires = DateTime.Now.AddMonths(1); if ((username == rdr[0].ToString()) && (password == rdr[1].ToString())) { Response.Redirect("HomePage.aspx"); // btnGo.PostBackUrl = "~/HomePage.aspx"; } else { lblErrMsg.Text = "User Name And Password didn't match please try again"; } } catch (Exception err) { lblErrMsg.Text = "Invalid Credentials"; } finally { con.Close(); } } }

Anas,why not provide the sample with encryption to store username or other details for login! i think its good to provide such sample here!

please send me this code for download

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. abiruban (1)