Introduction
In this blog, I will demonstrate how to create a login form with an encrypted password using ASP.NET step by step. I will decrypt the password from the database and login to the dashboard. Also, I will implement the sign out functionality using JavaScript.
Step 1
Open SQL Server 2014 and create database table UserRegistration.
- CREATE TABLE [dbo].[UserRegistration](
- [ID] [int] IDENTITY(1,1) NOT NULL,
- [Name] [nvarchar](50) NULL,
- [Email] [nvarchar](50) NULL,
- [PhoneNumber] [nvarchar](50) NULL,
- [Password] [nvarchar](50) NULL,
- [Created] [datetime] NULL,
- CONSTRAINT [PK_UserRegistration] PRIMARY KEY CLUSTERED
- (
- [ID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
- CREATE procedure [dbo].[spRegister]
- (
- @Name nvarchar(50),
- @Email nvarchar(50),
- @PhoneNumber nvarchar(50),
- @Password nvarchar(50),
- @Created datetime
- )
- as
- begin
- insert into [dbo].[UserRegistration](Name,Email,PhoneNumber,Password,Created)
- values(@Name,@Email,@PhoneNumber,@Password,GETDATE())
- end
- Create procedure [dbo].[spLogin]
- (
- @Email nvarchar(50),
- @Password nvarchar(50)
- )
- as
- begin
- Select COUNT(*) from UserRegistration where Email=@Email and Password=@Password
- end
Step 2
Open Visual Studio 2015, create an empty web application project and give it a meaningful name. Right-click or double-click on web config file and database connection in it.
- <connectionStrings>
- <add name="DBCS" connectionString="data source=DESKTOP-M021QJH\SQLEXPRESS; database=SampleDB; integrated security=true;"/>
- </connectionStrings>
Add the below line of code if you get a validation error.
- <appSettings>
- <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
- </appSettings>
Step 3
Right-click on the project, select Add, choose web form, and name it LoginForm.
Add the script and bootstrap 4 style plugin files in the header section of the login page.
- link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
- <link href="Content/bootstrap.min.css" rel="stylesheet" />
- <script src="scripts/jquery-3.3.1.min.js"></script>
- <script src="scripts/bootstrap.min.js"></script>
- <style>
- .bottom {
- margin-bottom: 5px !important;
- }
- </style>
- <script type="text/javascript">
- function preventBack() { window.history.forward(); }
- setTimeout("preventBack()", 0);
- window.onunload = function () { null };
- </script>
Design the web form using textbox control, button control, and validation control. Apply the respective bootstrap 4 class.
- <body>
- <form id="form1" runat="server">
- <div class="container py-4">
- <div class="col-md-5 offset-md-3">
- <div class="card card-outline-secondary rounded-0">
- <div class="card-header bg-success rounded-0">
- <h4 class="text-center text-uppercase text-white">Login</h4>
- </div>
- <div class="card-body">
- <div class="form-group bottom">
- <label>Username (Email)</label>
- <div class="input-group">
- <div class="input-group-prepend">
- <div class="input-group-text"><i class="fa fa-envelope"></i></div>
- </div>
- <asp:TextBox ID="txtEmail" runat="server" CssClass="form-control"></asp:TextBox>
- </div>
- <asp:RequiredFieldValidator ID="rfvEmail" Display="Dynamic" ControlToValidate="txtEmail" CssClass="text-danger" runat="server" ErrorMessage="Please enter email address"></asp:RequiredFieldValidator>
- <asp:RegularExpressionValidator ID="revEmail" ControlToValidate="txtEmail" CssClass="text-danger" runat="server" ErrorMessage="Enter valid email" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
- </div>
- <div class="form-group bottom">
- <label>Password</label>
- <div class="input-group">
- <div class="input-group-prepend">
- <div class="input-group-text"><i class="fa fa-lock"></i></div>
- </div>
- <asp:TextBox ID="txtPassword" TextMode="Password" runat="server" CssClass="form-control"></asp:TextBox>
- </div>
- <asp:RequiredFieldValidator ID="rfvPassword" ControlToValidate="txtPassword" CssClass="text-danger" runat="server" ErrorMessage="Please enter password"></asp:RequiredFieldValidator>
- </div>
- <div class="form-group">
- <asp:Button ID="btnLogin" CssClass="btn btn-success rounded-0 btn-block" runat="server" Text="Login" OnClick="btnLogin_Click" />
- </div>
- <div class="form-group text-center">
- <asp:HyperLink ID="linkRegistration" NavigateUrl="~/RegisterForm.aspx" CssClass="text-primary btn-link" runat="server">New User</asp:HyperLink>
- <asp:HyperLink ID="linkForgotPassword" NavigateUrl="~/ForgotPassword.aspx" CssClass="text-primary btn-link" runat="server">Forgot Password</asp:HyperLink>
- </div>
- <div class="text-center">
- <asp:Label ID="lblMessage" CssClass="text-center" runat="server"></asp:Label>
- </div>
- </div>
- </div>
- </div>
- </div>
- </form>
- </body>
Step 4
Double-click on the Login button and write the following C# code.
Add the following namespace.
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.Security.Cryptography;
- using System.IO;
- using System.Text;
Complete code of the login page -
- using System;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.IO;
- using System.Security.Cryptography;
- using System.Text;
-
- namespace UserRegistration_Demo
- {
- public partial class LoginForm : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- Session["Username"] = txtEmail.Text;
- }
- }
- private string Decrypt(string clearText)
- {
- string EncryptionKey = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
- byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
- using (Aes encryptor = Aes.Create())
- {
- Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
- encryptor.Key = pdb.GetBytes(32);
- encryptor.IV = pdb.GetBytes(16);
- using (MemoryStream ms = new MemoryStream())
- {
- using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
- {
- cs.Write(clearBytes, 0, clearBytes.Length);
- cs.Close();
- }
- clearText = Convert.ToBase64String(ms.ToArray());
- }
- }
- return clearText;
- }
- protected void btnLogin_Click(object sender, EventArgs e)
- {
-
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con=new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spLogin", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- cmd.Parameters.AddWithValue("@Email",txtEmail.Text.Trim());
- cmd.Parameters.AddWithValue("@Password", Decrypt(txtPassword.Text.Trim()));
- int Username = (Int32)cmd.ExecuteScalar();
- if (Username == 1)
- {
- Session["Username"] = txtEmail.Text;
- Response.Redirect("Welcome.aspx");
- Session.RemoveAll();
-
- }
- else
- {
- lblMessage.ForeColor = System.Drawing.Color.Red;
- lblMessage.Text = "Invalid username and password";
- }
- }
- }
- }
- }
Step 5
Run the project by pressing ctrl+F5.
Screenshot 1
Screenshot 2
If we have entered a wrong username or password.
Step 6
In the dashboard, add a link button.
- <asp:LinkButton ID="linkbtnSignOut" CssClass="nav-link text-white" runat="server" OnClick="linkbtnSignOut_Click">Sign out</asp:LinkButton>
Step 7
Double click on the sign out link button.
- using System;
-
- namespace UserRegistration_Demo
- {
- public partial class Welcome : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- lblUsername.Text = Session["Username"].ToString();
- }
- }
-
- protected void linkbtnSignOut_Click(object sender, EventArgs e)
- {
- Session.RemoveAll();
- Response.Redirect("LoginForm.aspx");
- }
- }
- }
Screenshot 4