Simple Login Project in ASP.NET


Introduction

We are aware about the security available on internet world. At least on every website we create account for authentications and authorizations. In this article we will be creating simple login form without using built-in login control.

Prerequisite

This article expect something from you as given below:

(i) You should know MS-SQL Server
(ii) You should have the basic knowledge of ASP.Net controls

Creating Database

To store the user's credentials for future login, we should have database. So, let's create it.

Database Name: myDb.mdf
Table Name: myTb
Column Names: 

Column Name
Data Type
Required or Not
name
varchar(50)
Not Checked
username
varchar(50)
Not Checked
password
varchar(50)
Not Checked
emailid
varchar(50)
Not Checked

 

Creating Database Configuration in web.config file

To create database configuration in web.config file, simply drag the 'myTb' table from Database Explorer on any form and now delete the dragged item from web page, it will create the configuration settings for your database in web.config file automatically. 

 
Here is your configuration in web.config file: 

<connectionStrings>
  <add name="myDbConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\myDb.mdf;Integrated Security=True;User Instance=True"
   providerName="System.Data.SqlClient" />
 </connectionStrings>

Create User Form

To create or register new user we should have a form as given below. You can ignore the side links, top banner and footer texts because they are occurring from master page. 

 

Column Name
ID
Other
TextBox
name
TextBox
username
TextBox
password
TextMode=Password
Textbox
emailid
Button
create
Text=Create User

To call for the database configuration setting from web.config file I have used a function:

public string GetConnectionString()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["myDbConnectionString1"].ConnectionString;
    }

I have used a execute named function in code behind to perform the insertion task when 'Create User' named button clicked: 

private void execution(string name, string username, string password, string emailid)
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        string sql = "INSERT INTO myTb (name, username, password, emailid) VALUES "
        + " (@name, @username, @password, @emailid)";
        try
        {
            conn.Open();

            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlParameter[] pram = new SqlParameter[4];

            pram[0] = new SqlParameter("@name", SqlDbType.VarChar, 50);
            pram[1] = new SqlParameter("@username", SqlDbType.VarChar, 50);
            pram[2] = new SqlParameter("@password", SqlDbType.VarChar, 50);
            pram[3] = new SqlParameter("@emailid", SqlDbType.Char, 10);

            pram[0].Value = name;
            pram[1].Value = username;
            pram[2].Value = password;
            pram[3].Value = emailid;

            for (int i = 0; i < pram.Length; i++)
            {
                cmd.Parameters.Add(pram[i]);
            }
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex_msg)
        {
            string msg = "Error occured while inserting";
            msg += ex_msg.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }
    }

Finally I have used to following code in 'Create User' button click event. In this event we have to check the database for the duplication. Because in login project duplications are never assumed even. If there is no any duplication found in code behind will create a new account. Here it is:

protected void create_Click(object sender, EventArgs e)
    {
        SqlDataSource sds = new SqlDataSource();
        sds.ConnectionString = ConfigurationManager.ConnectionStrings["myDbConnectionString1"].ToString();

        sds.SelectParameters.Add("name", TypeCode.String, this.name.Text);
        sds.SelectParameters.Add("username", TypeCode.String, this.username.Text);
        sds.SelectParameters.Add("password", TypeCode.String, this.password.Text);
        sds.SelectParameters.Add("emailid", TypeCode.String, this.emailid.Text);

        sds.SelectCommand = "SELECT * FROM [myTb] WHERE [username] = @username";

        DataView dv = (DataView)sds.Select(DataSourceSelectArguments.Empty);

        if (dv.Count != 0)
        {
            this.lblinfo.ForeColor = System.Drawing.Color.Red;
            this.lblinfo.Text = "The user already Exist!";
            return;
        }
        else
        { 
            execution(name.Text,username.Text,password.Text,emailid.Text);
            this.lblinfo.Text = "New User Profile has been created you can login now";this.name.Text = "";
            this.username.Text = "";
            this.password.Text = "";
            this.emailid.Text = "";
        }
    }

Login User Form

To create or register new user we have created a form but still we don't have any login form. So let's create the login form.

Control Name
ID
Other
TextBox
username
TextBox
password
Button
log
Text=Login 



Now we have to write some codes which will select the values from database @ values in textboxes. And if any values are not being selected (retrieved) in code behind then show the error message like 'Invalid username or password!'. And if it matches any record then will redirect to the secure page. Here one more big concept arises, is known as 'membership'. But his is out of this article. Let's take a look at code behind of login form. 

protected void log_Click(object sender, EventArgs e)
    {
        SqlDataSource sds = new SqlDataSource();
        sds.ConnectionString = ConfigurationManager.ConnectionStrings["myDbConnectionString1"].ToString();

        sds.SelectParameters.Add("username", TypeCode.String, this.username.Text);
        sds.SelectParameters.Add("password", TypeCode.String, this.password.Text);

        sds.SelectCommand = "SELECT * FROM [myTb] WHERE [username] = @username AND [password] = @password";

        DataView dv = (DataView)sds.Select(DataSourceSelectArguments.Empty);

        if (dv.Count == 0)
        {
            this.lblinfo.ForeColor = System.Drawing.Color.Red;
            this.lblinfo.Text = "Invalid username and password!";
            return;
        }
        else
        {
            this.Session["username"] = dv[0].Row["username"].ToString();
            Response.Redirect("securepage/SecurePage.aspx");
        }
    }

Almost we have done everything but still we are missing a major thing. If you run your project at this time will open the SecurePage.aspx without login also. But if you want to redirect the user for login and then with authentication can access the SecurePage.aspx we have to deny the access in SecurePage.aspx page or directly in particular directory. And also when user enters credentials then session variables remember it until user close his browser or click on logout button or link (generally we prefer to click on logout).

So let's take a look to deny the access:

  <location path="securepage">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>

</configuration>

And we also have to change the authentication mode to "Forms" like: 

<system.web>
    <authentication mode="Forms">
      <forms loginUrl="Login.aspx" />
    </authentication>
            <compilation debug="true"/>
</system.web>

Conclusion

We can also place our logins to MasterPage so that can be visible entirely in website. 

Comments

Popular posts from this blog

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples