Click here to Skip to main content
12,446,296 members (57,433 online)
Click here to Skip to main content
Add your own
alternative version


72 bookmarked

How to implement Two basics uses for the Login control 2.0 (login and RememberMe)

, 23 Nov 2006
Rate this:
Please Sign up or sign in to vote.
This article will show you how to implement two basics uses of the ASP.NET Login control (2.0), The login task itself to validate the users who’s trying to access your web site. In addition i will show how to implement the REMEMBERME process using cookies to save the user name inside the user PC


The login control is a good gift to save time in the way to make one of the most important tasks everytime that you developed a site, the login task (Who’s inside, Who’s outside)  Inside the next lines I will try give you a basic, but functional login control programming, which one you can use in your project.


The end of this program is to show the login page first (there is the login control) the user insert their login credentials (username, password) the page evaluates the credentials against a database, if the user exist and the password is the same saved onto database, the login page grant the access to welcome page, at negative case the login page is refresh showing a Login error message and set ready to attempt again.



Sample screenshot


Figure 1. The login process



First Step.

Start a new Project.

Start creating two forms, the login form and the welcome form (destination form).


*Login Form (login.aspx)

*Welcome Form (welcome.aspx)


Forms Controls.


Login Form (login.aspx)

Add the Login Control. (Logeo)


Welcome Form (welcome.aspx)

Add a label (Message)


Now let’s focus on login Control (named Logeo at this example)


If you want to change the default skin check the image below and click over automatic format>classic in order to change to windows XP skin.



Sample screenshot


Figure 2. The login control skin wizard.



That was a Skin change; now let’s make the logical changes to use the login control.

Keep all the properties by default, and change this one.


DestinationPageUrl  = welcome.aspx       At login true case goes to welcome.aspx

Be sure that the authenticated property is false (Login control).



Now let’s validate the user credentials wrote inside the textboxes, true case goes to the URL wrote on DestinationPageUrl property, false case reload the form.


This code on Login control authenticate process evaluates the users credentials and grant or deny the access to the destination page.



protected void Logeo_Authenticate(object sender, AuthenticateEventArgs e)
            string id_user = Logeo.UserName.Trim(); //Get the username from the control
            string pass_user = Logeo.Password.Trim(); //get the Password from the control


 //These are a sql and connection Examples

 string sql = "SELECT coduser, nameuser FROM users WHERE iduser = @param_Id AND passuser = @param_Password";
            public SqlConnection conexionExpress = new SqlConnection("server='localhost\\SQLExpress';Integrated Security=true;Initial Catalog=college;User Instance=false"); //Create the server connection

            SqlCommand comandoSql = new SqlCommand(sql, conexionExpress); //Create the sql command using sql string and sql connection

//Add the sql parameters

  comandoSql.Parameters.AddWithValue("@param_Id", id_user); //New on VS 2.0

  comandoSql.Parameters.AddWithValue("@param_Password", pass_user);

            string cod_user = "";
            string name_user = "";
            //Open database connection
            SqlDataReader dr = comandoSql.ExecuteReader();
            while (dr.Read())
                cod_user = dr.GetValue(0).ToString(); //The coduser is unique onto database table
                name_user = dr.GetValue(1).ToString();
            conexionExpress.Close();//Close Database Connection
            if (cod_user != "") //The user exist onto database
                /*Create the session vars
                Session["coduser"] = cod_user;
                Session["nameuser"] = name_user;
                e.Authenticated = true; //Grant the access, Goes to DestinationPageUrl
        catch(Exception)//On Login Error
            e.Authenticated = false;//Confirm that you are out

  conexionExpress.Close();//On any error case, close the database connection


Now we will change the welcome page to show the user name who grant the access


On welcome.aspx modify the load event


protected void Page_Load(object sender, EventArgs e)


        if (!IsPostBack)


            Message.Text = "Welcome " + Session["nameuser"].ToString() + " Your user code is " +  Session["coduser"].ToString();




At this point you already do the login event in you website, but we have a problem, ¿what happened if the user write the absolute url to welcome page?, he will reach the page, so lets add these lines at web.config file in order to redirect all the attempts to visit forms using absolute urls to login form.


Change the authentication mode to Forms and add the next in order to lock your site, and last define the login form URL like the default form.



<authentication mode="Forms">

<forms loginUrl="login.aspx" protection="All" defaultUrl="login.spx">




To prevent that anonymous users try to access our site, we have to modify the authorization element over the web.config file.



     <deny users=?/>



We these previous lines we are denying the access to all anonymous users.




Sample screenshot


Figure 3. There is only one way to go inside your website, thats the login form



Right now we fulfilled the objectives, all the attempts to get any form inside our website are redirect to login form, and only the registered user can go trough this form.


Now lets implement the remember me next time process in order to save the username inside a cookie, and everytime that the user load the login pagem we can read the username from the cookie.


Here the logical process


Sample screenshot


Figure 4. logical process to read and Create cookies over the pc client.


You can see in the previous picture that the first process to implement is read the cookie from the user PC, if it exist (cookie) read the cookie and write the username parameter inside the login control username textbox.


Here process must to be implement onload process (login.aspx).


protected void Page_Load(object sender, EventArgs e)


       if (!IsPostBack)//On first time


            if (Request.Cookies["myCookie"] != null) //Cookie Exists??


                HttpCookie cookie = Request.Cookies.Get(myCookie");

                string user = cookie.Values["user"].ToString();

                if (user != "")


                    Logeo.UserName = user; //Write the username onto login username textbox 






Already the read cookie process, now we have to implement the other task, write the user name to the cookie.



Sample screenshot


Figure 5. Remember check the box.



When you press the login button a logged in process is fired up, we must to write the create process synthax for the cookie at this time, check the next code lines.


protected void Logeo_LoggedIn(object sender, EventArgs e)


      CheckBox chBox = (CheckBox)Logeo.FindControl("RememberMe");

      if (chBox.Checked)


          HttpCookie myCookie = new HttpCookie("myCookie"); //Instance the new cookie

          Response.Cookies.Remove("myCookie"); //Remove previous cookie

          Response.Cookies.Add(myCookie); //Create the new cookie

          myCookie.Values.Add("user", this.Logeo.UserName); //Add the username field to the cookie

          DateTime deathDate = DateTime.Now.AddDays(15); //Days of life

          Response.Cookies["myCookie"].Expires = deathDate; //Assign the life period


          myCookie.Values.Add("pass", this.Logeo.Password);




That was the implementation for remember me next time feature using cookies to save onto the user pc, be carefully with all the information that you save there. Because an experienced user could read it.



There are more and complicated ways to login registered users, so this is one of the most basics and easy to implement login tasks, enjoy it.

This task look hard but you can do it as easy as you want, feel Free to make any changes.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Britney S. Morales
Web Developer
Colombia Colombia
Web Developer during 3 years and counting, i worked over my school website by two years, right now im webmaster at World Wowan foundation banking in my home city.

Please forgive my pictures examples, they are at spanish language because its my mother language.

You may also be interested in...


Comments and Discussions

QuestionLogin for ASP.Net Pin
Member 106126828-Feb-08 19:44
memberMember 106126828-Feb-08 19:44 
AnswerRe: Login for ASP.Net Pin
Britney S. Morales13-Jun-08 4:27
memberBritney S. Morales13-Jun-08 4:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160811.3 | Last Updated 23 Nov 2006
Article Copyright 2006 by Britney S. Morales
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid