Trick – How to implement Session Authentication In ASP.NET

Trick – How to implement Session Authentication In ASP.NET

What is Authentication

Authentication is a process of identifying a person. It is commonly done through the use of login page which asks a user to enter his username and password. In ASP.NET websites you can do the authentication of a user by matching his user id and password with the one stored in the database. If both his username and password matches only then he is allowed to view secured areas of the website.

External providers like Google can also authenticate users. Check this Google Contacts API tutorial where I have created a Google APP to authenticate users using Google APIs

In this tutorial I will show how to do Session Authentication in your website. When the user is authenticated I store a key called Authenticate with value true, in the session variable. This key is checked in all the secured pages, if it does not contain true value then the user is redirected to the login page.

HTML Of the Login Page

In our login page I have two textboxes one for User Name and other for Password. There is also a submit button at the end, on whose click this authentication code should run. The label lblMsg is used to show the authentication message.

<table>
<tr>
    <td colspan="2">
        <b>
            <asp:Label ID="lblMsg" runat="server"></asp:Label>
        </b>
    </td>
</tr>
<tr>
    <td>
        User Name
    </td>
    <td>
        <asp:TextBox ID="txtUserName" runat="server" MaxLength="50"></asp:TextBox>
    </td>
</tr>
<tr>
    <td>
        Password
    </td>
    <td>
        <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
    </td>
</tr>
<tr>
    <td colspan="2">
        <asp:Button ID="submitButton" runat="server" OnClick="submitButton_Click" />
    </td>
</tr>
</table>

The click Event of the Submit Button

In the click event of the button I passing the username and password, which the user types, in the textboxes to the stored procedure called sp_AuthenticateUser. The work of this stored procedure is to match the username and password stored in the database.

Entity Framework Core – Do you know that with Entity Framework Core, you can also do inserting of data, and all other database operations just like ADO.NET.

If they matches then the message Authentication Successful is shown in the message label and a Session key called Authenticate is created. The the user is redirected to the secured page.

protected void submitButton_Click(object sender, ImageClickEventArgs e)
{
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString=ConfigurationManager.ConnectionStrings["OtcCS"].ConnectionString;

    SqlCommand cmd = new SqlCommand("sp_AuthenticateUser", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 100);
    cmd.Parameters.Add("@password", SqlDbType.VarChar, 50);
    cmd.Parameters.Add("@msg", SqlDbType.VarChar, 50);
    cmd.Parameters["@UserName"].Value = txtUserName.Text;
    cmd.Parameters["@password"].Value = txtPassword.Text;
    cmd.Parameters["@msg"].Direction = ParameterDirection.Output;

    conn.Open();
    int i = cmd.ExecuteNonQuery();
    conn.Close();

    string msg = cmd.Parameters["@msg"].Value.ToString();
    lblMsg.Text = msg;

    if (msg == "Authentication Successful")
    {
        Session["Authenticate"]="true";
        Response.Redirect("securedpage.aspx");
    }
}

The Stored Procedure which check the Username and Password

CREATE proc [dbo].[sp_Authenticate]
@UserName     varchar(100),
@password     varchar(50),
@msg          varchar(50)=null output

AS
declare @rowcount  int
select @rowcount=count(*) from AdminUser where [email protected] and cast(password as varbinary)=cast(@password as varbinary)

IF @rowcount &amp;lt;&amp;gt; 0
BEGIN
 SET @msg = 'Authentication Successful'
END
ELSE
BEGIN
  SET @msg = 'Invalid LoginId or Password'
END

Note that the usernames and passwords are stored in the database table called AdminUser. It has just two columns which are given below.

1. UserName             varchar(100)

2. Password                varchar(50)

Secured Pages

It should be noted that I also check the value of the session key in all our secured page so that user does not simply type the secured page’s URL and access it.

To do this – In the Page Load event of all the secured pages, add the following code.

protected void Page_Load(object sender, EventArgs e)
{
    if (Convert.ToString(Session["Authenticate"]) !="true")
    {
        Response.Redirect("~/login.aspx");
    }
}

Thus in this way you can easily do Session Authentication in Asp.Net.

Are your starting with ADO.NET programming, then you should look into this very first tutorial which explains how to Insert Data in a Database using C# and ASP.NET.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.