In this article, we will learn how to create a simple user authentication system in Asp.Net using C#. The user’s credentials will be saved in the database and will be retrieved to verify the login information.

Create a login module using ASP.NET

In this tutorial, The login system consists of two pages.

Login Page: Login.aspx will contain the View representation of the login form.

Dashboard: Dashboard.aspx is the user’s account page and will be redirected to if the user is successfully logged in.

The Database

Create the Users table in a SQL Server database as shown below

SET ansi_nulls ON 
go 
SET quoted_identifier ON 
go 

CREATE TABLE [dbo].[users] 
  ( 
     [id]       [INT] IDENTITY(1, 1) NOT NULL, 
     [name]     [NVARCHAR](50) NULL, 
     [username] [NVARCHAR](50) NULL, 
     [password] [NVARCHAR](50) NULL 
  ) 
ON [PRIMARY] 

go

HTML

The login page contains a login control. This control call the isValidUser function on the event OnAuthenticate

<form id="form1" runat="server">
<asp:Login ID = "Login1" runat = "server" OnAuthenticate= "isValidUser"></asp:Login>
</form>

CSS

<style type="text/css">.LoginControl {
	background-color: Highlight;
	border-color: darkmagenta;
	border-style: solid;
	border-width: 1px;
	color: black;
	font-family: 'Times New Roman';
	font-size: 16px;
}

</style>

Namespaces

You need to import the following namespaces.

using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Security;

Stored Procedure

To validate the user’s login information, the following stored procedure is used. It will checks whether the username and password being entered are correct. I will return the UserId if the user/password combination is right, or ‘-1’ if the authentication failed.

CREATE PROCEDURE [dbo].[Usp_validateuser] @UserName NVARCHAR(20), 
                                          @Password NVARCHAR(20) 
AS 
  BEGIN 
      SET nocount ON; 

      DECLARE @UserId INT 

      SELECT @UserId = id 
      FROM   users 
      WHERE  username = @Username 
             AND [password] = @Password 

      IF @UserId IS NOT NULL 
        BEGIN 
            SELECT @UserId [UserId] 
        END 
      ELSE 
        BEGIN 
            SELECT -1 
        END 
  END

Now insert one record into that table for a testing purpose

USE [Books] 

go 

INSERT INTO [dbo].[users] 
            ([name], 
             [username], 
             [password]) 
VALUES      ('User 1', 
             'user1', 
             'user1234') 

go
Note: in a real-life login system, the password should never be saved as a plain text. Instead, it should be encrypted for security purposes.

IsValidUser function

The function below check if user information entered is valid by passing the username and password to the Store procedure we created earlier.

    protected void isValidUser(object sender, EventArgs e)
    {
        int userId = 0;
        string conn_str = "Data Source=localhost;Initial Catalog=Books;Integrated Security=True";
        using (SqlConnection conn = new SqlConnection(conn_str))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "USP_ValidateUser";
                cmd.Parameters.AddWithValue("@username", lgn.UserName);
                cmd.Parameters.AddWithValue("@password", lgn.Password);
                cmd.Connection = conn;
                conn.Open();
                userId = Convert.ToInt32(cmd.ExecuteScalar());
                conn.Close();
            }
            switch (userId)
            {
                case -1:
                    lgn.FailureText = "Wrong login information";
                    break;
            
                default:
                    FormsAuthentication.RedirectFromLoginPage(lgn.UserName, lgn.RememberMeSet);
                    break;
            }
        }
    }

If the user’s information entered is correct, the user will be directed to the dashboard.aspx.

The dashboard.aspx will display the username and login status of the user being logged in.

    <form id="form1" runat="server">
        <div>
            Welcome
            <asp:LoginName ID="LoginName" runat="server" Font-Bold="true" />
          
            <br />
            <asp:LoginStatus ID="LoginStatus" runat="server" />
        </div>
    </form>

You need to import the following namespace.

using System.Web.Security;

Inside the page load event, verify if the authenticated user accesses the page, or else the user is redirected back to the login page.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.Page.User.Identity.IsAuthenticated)
        {
            FormsAuthentication.RedirectToLoginPage();
        }
    }

Set the authentication mode to Forms in the web.config file, as shown below.

    <authentication mode="Forms">
      <forms defaultUrl="~/Dashboard.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="1000"></forms>
    </authentication>

Relate Articles

Last modified: October 6, 2019

Comments

Write a Reply or Comment

Your email address will not be published.