Click here to Skip to main content
15,867,704 members
Articles / Web Development / ASP.NET
Article

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

Rate me:
Please Sign up or sign in to vote.
3.27/5 (32 votes)
23 Nov 20066 min read 401.2K   72   91
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

Introduction

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.<o:p>

<o:p> 

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.

<o:p> 

<o:p> 

<o:p><o:p>Sample screenshot

<o:p> 

<o:p>

Figure 1. The login process

 

 

First Step.<o:p>

<o:p>

Start a new Asp.net Project.<o:p>

<o:p>

Start creating two forms, the login form and the welcome form (destination form).<o:p>

<o:p> 

*Login Form (login.aspx)<o:p>

*Welcome Form (welcome.aspx)<o:p>

<o:p> 

Forms Controls.<o:p>

<o:p> 

Login Form (login.aspx)<o:p>

Add the Login Control. (Logeo)<o:p>

<o:p> 

Welcome Form (welcome.aspx)<o:p>

Add a label (Message)<o:p>

<o:p> 

<o:p>

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.<o:p>

<o:p> 

<o:p> 

Sample screenshot

 

Figure 2. The login control skin wizard.

 

<o:p>

<o:p> 

That was a Skin change; now let’s make the logical changes to use the login control.<o:p>

Keep all the properties by default, and change this one.<o:p>

<o:p> 

DestinationPageUrl  = welcome.aspx       At login true case goes to welcome.aspx <o:p>

<o:p>

<o:p>

Be sure that the authenticated property is false (Login control).<o:p>

<o:p>

 

<o:p> 

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)
{
        try
        {
            string id_user = Logeo.UserName.Trim(); //Get the username from the control
            string pass_user = Logeo.Password.Trim(); //get the Password from the control

            <o:p>

 //These are a sql and connection Examples<o:p>

 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
                        
            conexionExpress.Open();
            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
        }<o:p>

}<o:p>

Now we will change the welcome page to show the user name who grant the access<o:p>

 

On welcome.aspx modify the load event

 

protected void Page_Load(object sender, EventArgs e)<o:p>

 {<o:p>

        if (!IsPostBack)<o:p>

        {<o:p>

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

        }<o:p>

 }<o:p>

 

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.<o:p>

<o:p> 

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.

<o:p> 

<o:p>

 

<authentication mode="Forms"><o:p>

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

</forms><o:p>

</authentication>

 

<o:p>

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

 

<authorization>

     <deny users=?/>

</authorization><o:p>

 

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<o:p>

 

 

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)<o:p>

{<o:p>

       if (!IsPostBack)//On first time

       {<o:p>

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

            {<o:p>

                HttpCookie cookie = Request.Cookies.Get(myCookie");<o:p>

                string user = cookie.Values["user"].ToString();<o:p>

                if (user != "")<o:p>

                {<o:p>

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

                }<o:p>

            }<o:p>

       }<o:p>

 }

<o:p> 

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

<o:p> 

 

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)<o:p>

{<o:p>

      CheckBox chBox = (CheckBox)Logeo.FindControl("RememberMe");<o:p>

      if (chBox.Checked)<o:p>

      {<o:p>

          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<o:p>

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

          //IF YOU WANT SAVE THE PASSWORD TOO (IT IS NOT RECOMMENDED)

          myCookie.Values.Add("pass", this.Logeo.Password);<o:p>

      }

}<o:p>

 

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.

 

Conclusion

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.

License

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


Written By
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.


Comments and Discussions

 
QuestionCant make the C# version works Pin
John Kh14-Apr-08 21:45
John Kh14-Apr-08 21:45 
AnswerRe: Cant make the C# version works Pin
Britney S. Morales13-Jun-08 4:24
Britney S. Morales13-Jun-08 4:24 

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.