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






3.27/5 (32 votes)
Nov 3, 2006
6 min read

419340

706
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.
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.
Figure 1. The login process
First Step.
Start a new Asp.net 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.
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) //These are a sql and connection Examples string sql = "SELECT coduser, nameuser FROM users WHERE iduser = @param_Id AND passuser = @param_Password"; //Add the sql parameters comandoSql.Parameters.AddWithValue("@param_Id", id_user); //New on VS 2.0 comandoSql.Parameters.AddWithValue("@param_Password", pass_user); conexionExpress.Close();//On any error case, close the database connection }
{
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
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
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
}
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">
</forms>
</authentication>
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>
We these previous lines we are denying the access to all anonymous users.
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
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.
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
//IF YOU WANT SAVE THE PASSWORD TOO (IT IS NOT RECOMMENDED)
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.
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.