Login page is the basic need of any Application. The user information needs to be validated in the system before doing any action in the system.We will create a login form step by step.
Create a database named ConsumerBanking.
Create a table named CBLoginInfo
- create database ConsumerBanking
-
- go
-
- USE [ConsumerBanking]
- GO
-
- /****** Object: Table [dbo].[CBLoginInfo] Script Date: 8/7/2016 10:06:47 PM ******/
- SET ANSI_NULLS ON
- GO
-
- SET QUOTED_IDENTIFIER ON
- GO
-
- CREATE TABLE [dbo].[CBLoginInfo](
- [CustomerId] [int] NOT NULL,
- [UserName] [nvarchar](20) NULL,
- [Password] [nvarchar](20) NULL,
- [LastLoginDate] [datetime] NULL,
- [LoginFailedCount] [int] NULL,
- [LoginIPAddress] [nvarchar](20) NULL,
- [CustomerTimeZone] [nvarchar](20) NULL,
- [LastAccessedDate] [datetime] NULL,
- [AccountLocked] [bit] NULL,
- CONSTRAINT [PK_CBLogin1] PRIMARY KEY CLUSTERED
- (
- [CustomerId] 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
Note: Passwords are never stored in the plain text in any Application. It should be encrypted, so that no one can read it. For demonstration purposes, it is plain text now.
Once some records are inserted into the SQL Server database, we will write a stored procedure to fetch the user information and validate the user information.
We will create a stored procedure, named GetCBLoginInfo.
There is the logic, which we will achieve in the stored procedure, as this logic is common in any login page.
- If a user name and password is valid, it is a successful login and redirects the user to the landing page.
- If a username does not exist in the database, it shows the error 'User Does not Exist'.
- If the user is a valid user and wrong password is given by the user, it will give the message, number of failed attempts.
- If failed attempt is more than or equal to 5 times, it will lock the user out.
- USE [ConsumerBanking]
- GO
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
-
- CREATE PROCEDURE [dbo].[GetCBLoginInfo]
- @UserName VARCHAR(20),
- @Password varchar(20)
- AS
- SET NOCOUNT ON
- Declare @Failedcount AS INT
- SET @Failedcount = (SELECT LoginFailedCount from CBLoginInfo WHERE UserName = @UserName)
-
- IF EXISTS(SELECT * FROM CBLoginInfo WHERE UserName = @UserName)
-
- BEGIN
-
- IF EXISTS(SELECT * FROM CBLoginInfo WHERE UserName = @UserName AND Password = @Password )
- SELECT 'Success' AS UserExists
- ELSE
-
- Update CBLoginInfo set LoginFailedCount = @Failedcount+1 WHERE UserName = @UserName
-
- Update CBLoginInfo set LastLoginDate=GETDATE() WHERE UserName = @UserName
- BEGIN
- IF @Failedcount >=5
-
-
- SELECT 'Maximum Attempt Reached (5 times) .Your Account is locked now.' AS UserExists
- ELSE
-
- select CONVERT(varchar(10), (SELECT LoginFailedCount from CBLoginInfo WHERE UserName = @UserName)) AS UserFailedcount
- END
- END
- ELSE
-
- BEGIN
-
- SELECT 'User Does not Exists' AS UserExists
- END
We have created the stored procedure. Our database
part is ready now.
Now, we will create ASP.NET MVC Web Application to
create a login page .We will call the stored procedure, using Entity framework
to validate the user information from the database.
Create a new project and select ASP.NET Web Application. Click OK.
Select MVC and click OK.
The MVC project is created now.
We will use Entity Framework as a data fetching layer. We will add an EDMX file to fetch the data from the database. We will call the stored procedure, which we created earlier.
Select the option Generate from the database.
Select your database Server and the database tables in the next step.
Select the stored procedure in the next step.
Click Finish. Now, ADO.NET Entity Data Model is created for us.
We will create a new model class, named CBUserModel, which has two properties, named UserName and Password. This model class will be used to communicate between the view and controller. We have some basic validation to validate the user Name and the Password fields will not to be blank, using DataAnnotations from the System.ComponentModel.
- using System.ComponentModel.DataAnnotations;
-
- namespace CBLogin.Models
- {
- public class CBUserModel
- {
- [Required(ErrorMessage = "UserName is required")]
- public string UserName { get; set; }
- [Required(ErrorMessage = "Password is required")]
- [DataType(DataType.Password)]
- public string Password { get; set; }
- }
- }
We will create a controller, named CBLoginController, which has the actions, given below:The Index view will return us the Index view.
- public ActionResult Index()
- {
- return View();
- }
This Index action with [Httppost] verb will be called, when the user posts the data after entering UserName and Password field. In this action, the Username and Password will be validated against the database.
- [HttpPost]
- public ActionResult Index(CBUserModel model)
- {
- ConsumerBankingEntities cbe = new ConsumerBankingEntities();
- var s = cbe.GetCBLoginInfo(model.UserName, model.Password);
-
- var item = s.FirstOrDefault();
- if (item == "Success")
- {
-
- return View("UserLandingView");
- }
- else if(item=="User Does not Exists")
-
- {
- ViewBag.NotValidUser = item;
-
- }
- else
- {
- ViewBag.Failedcount = item;
- }
-
- return View("Index");
- }
The action UserLandingView will be called, when the user posts the data after entering UserName and Password field. There is a successful login.
- public ActionResult UserLandingView()
- {
- return View();
- }
Index View
In the Index view, we have two input textbox fields, named UserName, Password and a Login button.
- @model CBLogin.Models.CBUserModel
-
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1">
-
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
- <style type="text/css">
- .bs-example {
-
- height:220px;
-
- }
-
- .centerlook {
- padding-left: 400px;
- font-weight: bold;
- width: 1000px;
- }
- .error {
- padding-left: 400px;
- font-weight: bold;
- width: 1000px;
- color: red;
- }
-
- .loginbtn {
- padding-left: 500px;
- }
- </style>
-
- </head>
- <body>
-
- @using (Html.BeginForm())
- {
- <div class="bs-example" style="border:2px solid gray;">
-
- <div class="form-group centerlook">
- <h1> Login </h1>
- </div>
- <div class="form-group centerlook">
- <label>User Name: </label>
- @Html.EditorFor(model => model.UserName)*
- @Html.ValidationMessageFor(model => model.UserName)
- </div>
- <div class="form-group centerlook">
- <label>Password:</label>
- @Html.EditorFor(model => model.Password) *
- @Html.ValidationMessageFor(model => model.Password)
-
- </div>
- <div class="form-group error">
- @if (@ViewBag.Failedcount != null)
- {
-
- <label> Failed Attempt count is: @ViewBag.Failedcount</label>
- }
-
- @if (@ViewBag.NotValidUser != null)
- {
-
- <label> @ViewBag.NotValidUser</label>
- }
- </div>
- <div class="loginbtn">
-
- <input type="submit" value="Login" class="btn btn-primary" />
-
- </div>
- </div>
- }
- </body>
- </html>
When a user loads the Index action, the Index view will be loaded. When the user enters UserName, Password and clicks the Login button, the Index action with HttpPost attribute is called.
The Entity framework code validates the username and password, given below. Based on the status returned from the stored procedure, the user will be shown an error message or redirected to the landing page.
When we run the page, we get the output of the page, as
we have stated in the starting of the topic.
Condition 1: If the User Name and Password is blank, it will show the Validation Error Message, as shown in the screen, given below. We can add regular expression and other validation with the help of Component Model .
Condition 2: If a User Name and Password is given by the user and UserName does not exist in the database /system, it shows message to the user “User Does not Exists”, as shown in the screen, given below:
Condition 3: If the User Name and Password given by the user is a valid user and username and password is correct, the user will be navigated to the landing page view.
Condition 4: If the User Name and Password is given wrong for five times or more than five times, then the user account will be locked, as shown in the screen, given below:
Condition 5: If the User Name and Password is given wrong, the page will display the number of failed attempts done by the user .
We created a login page in ASP.NET MVC. I hope this will be useful. Thanks for reading.