Monday, 9 February 2015

Step by Step Explanation for creating a Login page and Authenticating the users in Asp.Net

INTRODUCTION:

      In this article,I will give a detailed explanation for creating a login page ,authenticating the users and navigating the users to next page if the authentication is successful !! This article is a continuation of my  article  How to store the user details in a database .Read that article if you haven't,before continuing with this !!


HOW TO CREATE A LOGIN PAGE ???


         Create a web form with 2 labels ,2 textbox and 1 button. Give web form a name and I have given login.aspx

  


WHAT IS THE LOGIC WE ARE SUPPOSED TO IMPLEMENT NOW ??

   Let me now explain what we are supposed to do now..!! Consider 'facebook' . We will register to fb if we are a new user and for the next time we will give our registered 'mail id' and 'password'
    When we give those details ,fb will check with the database .. !! ok this man has given his email and password and I must check if those details matches with the details given by him during the time of registration and let me allow him to the profile page if the details are crystal clear !
     If you have given as 

       honey as your name
       honey@gmail.com as your mail id
    honeycomb as your password during the time of registration .

 While you login, you will give

   honey@gmail.com as your mail id
   honeycomb as password 

Now fb will check these details with the database . If the email id and password matches it will authenticate and navigate to the profile page else it will throw out error!! 
      We are going to implement the same logic here . While logging in , we are going to check whether the username and password perfectly matches with the one given during the time of registration !!

BUT HOW ??

        Do we need any table again ?? Do we need another database??
My answer is a big no !!! Our beloved Stored procedure is doing this phenomenal job !! 
       As I had said earlier we need a single stored procedure to check whether the username and password matches with the database.
      Create a stored procedure .(If you are new to that, read my previous article How to store the user details in a database )
     Copy the code below and I have given the name as 'spAuthentication '

  CREATE PROCEDURE [dbo].[spAuthentication]
@name nvarchar(500),
@password nvarchar(100)
as
Begin
Declare @count int
Select @count=COUNT(name)from RegistrationUserTbl
where [name]=@name and [password]=@password
if(@count=1)
Begin
Select 1 as ReturnCode
End
Else
Begin
Select -1 as Returncode
End
End
GO

 CODE EXPLANATION ...

       We have created 2 parameters and an integer 'count' . 
       We are selecting the name and password from the RegistrationUserTbl (created in previous article)
         But we are supposed to select which value ?? We must select the value which we are passing as the parameter

  where [name]=@name and [password]=@password

clearly implies we must select name which is passed as parameter '@name' and select password which is passed as parameter '@password' .We are telling the stored procedure to select these values from the RegistrationUserTbl
        The count returns 1 if the username and password exists .If the count value is 1 it will return 1 as Returncode else it will return -1 as Returncode. We will use the returncode to authenticate and I will explain later about this !! 
        Now,we need to pass parameters from the visual studio project for authenticating..!!

   
         
         protected void Button1_Click(object sender, EventArgs e)
        {

             if (AuthenticateUser(UserText.Text, PassText.Text))
              {
                Response.Redirect("~/Welcome.aspx", true);
            
              }
            else
            {
            ErrorLbl.Text = "Invalid Username or Password";
            }
     }
        private bool AuthenticateUser(string username, string password)
        {
            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("spAuthentication", con);
                cmd.CommandType = CommandType.StoredProcedure;
                string encryptpassword = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");
                SqlParameter parauserStaff = new SqlParameter("@username", username);
                SqlParameter parapasStaff = new SqlParameter("@password", encryptpassword);
                cmd.Parameters.Add(parauserStaff);
                cmd.Parameters.Add(parapasStaff);
                con.Open();
                int Returncode = (int)cmd.ExecuteScalar();
                return Returncode == 1;
            }
        }
  



CODE EXPLANATION:

              On clicking the login button (Buttontbl1 in this case) ,the method AuthenticateUser is called and we are passing the parameters as 'username' and 'password' and where the usename and password is coming from??Those are coming from the 2 textboxes and so the line,

           if (AuthenticateUser(UserText.Text, PassText.Text))


  But what does the 'if' in the above code implies ??
  It implies " if  the AuthenticateUser method returns true,then redirect the user to 'Welcome.aspx' else throw out the error !!!
   As soon as the above line is executed, 

  private bool AuthenticateUser(string username, string password)

 is called and the code below those starts executing !!
 We are establishing the connection and we are calling the stored procedure spAuthentication which we had created earlier .!!
   Usually we will supply the values for parameter as
   
     SqlParameter username = new SqlParameter("@username", TextBoxStu.Text);
    But since we have passed the values for parameter while calling the method, its enough if we pass the name of the arguments
    See image below for details

   

  

We are encrypting the password before passing as a parameter ,opening the connection ,executing the stored procedure and  note the stored procedure returns 1 if the username and password exists.            
                         Select 1 as ReturnCode 
Note the AuthenticateUser method is a 'boolean' ,meaning it will return true or false. If the ReturnCode is 1 from the storedProcedure then the method will return true and the                        if (AuthenticateUser(UserText.Text, PassText.Text)) gets executed .If the method returns false (ReturnCode is -1) the 'else' part gets executed..!!

HURRAHHH..!!   YOU ARE DONE ... !!

     Run the webform1.aspx .Its the registration page .As you can see I entered # in contact number and javascript is doing his validation work properly !!

     


    

      After successful validation javascript is letting me to submit the form

   


    On Submitting the form ,I am redirected to login page , I have registered with name 'Anusha' and when I give my name as Anuks I am getting the error to enter valid username or password !!

     

 Upon giving my correct username and password I will be redirected to next page !!




       This is the welcome page which I got after successful login !!

 NOTE:
   Look at the image below !! Usually we will be having login page like this .We will ask the user to register if he /she is a new user else ,login as an existing user.But we have designed like  Registration page as the first page and next page as login page !!! Its just to show you how to authenticate the user during login !Use the same concept as we have seen in this article and try designing the page as below !! 

       


        
CONCLUSION:

    So that's all folks !! Clap your hands as we have created a flawless login page ,authenticated users and navigated to welcome page !! Hope you all like this post !! Write your comments ,Share with your friends , recommend on g+ .It helps me post more  !! Thanks for spending your valuable time in reading this post !! Hope its worth for !! Email me for queries :) Stay updated with upcoming articles too :)



No comments :

Post a Comment