- CREATE PROCEDURE spValidateUserLogin
- (
- @LoginID VARCHAR(20) ,
- @LoginPassword VARCHAR(20)
- )
- AS
- BEGIN
-
- DECLARE @authentication VARCHAR(10)='Failed'
-
- IF EXISTS(SELECT 1 FROM sysUser WHERE UserID=@LoginID AND UserPassword =@LoginPassword)
- BEGIN
- SET @authentication='Success'
- END
-
- SELECT @authentication AS isAuthenticated
-
- END
We are allowing only the unique User id for our application. Hence, if a user tries to register with an already existing User ID, this procedure will return ‘Failed’.
Now, our Database part has been completed. So, we will proceed to create the MVC application using Visual Studio.
Create MVC Web Application
Open Visual Studio and select File >> New >> Project.
After selecting the project, a "New Project" dialog will open. Select .NET Core inside Visual C# menu from the left panel. Then, select “ASP.NET Core Web Application” from available project types. Put the name of the project as
CookieAuthDemo and press OK. Refer to this image.
After clicking on OK, a new dialog will open asking to select the project template. You can observe two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.0” from these dropdowns. Then, select “Web application(Model-View-Controller)” template and press OK.
Now our project will open. You can observe in the solution explorer that we have Models, Views and Controllers folders already created. We will be adding our files to these folders only.
Adding the Model to the Application
Right click on Models folder and select Add >> Class. Name your class UserDetails.cs. This class will contain our User model properties. Add one more class file to Models folder. Name it as UserDetailsDataAccessLayer.cs . This class will contain our Database related operations.
Now, the Models folder has the following structure.
Open
User.cs and put the following code in it. Since we are adding the required validators to the fields of User class, so we need to use System.ComponentModel.DataAnnotations at the top. Also, to mask the values typed in Password field, we have used [DataType(DataType.Password)] property.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace CookieAuthDemo.Models
- {
- public class UserDetails
- {
- [Required]
- [Display(Name = "First Name")]
- public string FirstName { get; set; }
-
- [Required]
- [Display(Name = "Last Name")]
- public string LastName { get; set; }
-
- [Required]
- [Display(Name = "User ID")]
- public string UserID { get; set; }
-
- [Required]
- [Display(Name = "Password")]
- [DataType(DataType.Password)]
- public string Password { get; set; }
- }
- }
We will be reading our connection string from appsettings.json file. So open your appsettings.json file and put the following code into it. Make sure to put your connection string.
- {
- "Logging": {
- "IncludeScopes": false,
- "LogLevel": {
- "Default": "Warning"
- }
- },
- "ConnectionStrings": {
- "myConString": "Your connection string here"
- }
- }
Now, open UserDataAccessLayer.cs and put the following code to handle database operations.
- using Microsoft.Extensions.Configuration;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.SqlClient;
- using System.IO;
-
- namespace CookieAuthDemo.Models
- {
- public class UserDataAccessLayer
- {
- public static IConfiguration Configuration { get; set; }
-
-
- private static string GetConnectionString()
- {
- var builder = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("appsettings.json");
-
- Configuration = builder.Build();
-
- string connectionString = Configuration["ConnectionStrings:myConString"];
-
- return connectionString;
-
- }
-
- string connectionString = GetConnectionString();
-
-
- public string RegisterUser(UserDetails user)
- {
- using (SqlConnection con = new SqlConnection(connectionString))
- {
- SqlCommand cmd = new SqlCommand("spRegisterUser", con);
- cmd.CommandType = CommandType.StoredProcedure;
-
- cmd.Parameters.AddWithValue("@FirstName", user.FirstName);
- cmd.Parameters.AddWithValue("@LastName", user.LastName);
- cmd.Parameters.AddWithValue("@UserID", user.UserID);
- cmd.Parameters.AddWithValue("@UserPassword", user.Password);
-
- con.Open();
- string result = cmd.ExecuteScalar().ToString();
- con.Close();
-
- return result;
- }
- }
-
-
- public string ValidateLogin(UserDetails user)
- {
- using (SqlConnection con = new SqlConnection(connectionString))
- {
- SqlCommand cmd = new SqlCommand("spValidateUserLogin", con);
- cmd.CommandType = CommandType.StoredProcedure;
-
- cmd.Parameters.AddWithValue("@LoginID", user.UserID);
- cmd.Parameters.AddWithValue("@LoginPassword", user.Password);
-
- con.Open();
- string result = cmd.ExecuteScalar().ToString();
- con.Close();
-
- return result;
- }
- }
- }
- }
Our Models has been created. So, we will proceed to add controllers to our application.
Adding the Controller to the Application
Right click on Controllers folder and select Add >> New Item.
An “Add New Item” dialog box will open. Select Web from the left panel, then select “MVC Controller Class” from templates panel, and put the name as LoginController.cs. Press OK. This controller will handle the logic for Registering new user and login into the application.
Similarly, add one more controller, UserController.cs. This controller will contain a home page for user, which will be available to authorized users only.
Adding Views to the Application
To add views for our controller class, we need to create a folder inside Views folder with the same name as our controller and then add our views to that folder. Since we have two controllers for this application. Hence, we will be creating two folders inside views folder
Right-click on the Views folder, and then Add >> New Folder and name the folder as Login. Similarly, add one more folder User into the view folder.
Now, right-click on the Views/Login folder, and then select Add >> New Item.
An “Add New Item” dialog box will open. Select Web from the left panel, then select “MVC View Page” from templates panel, and put the name as RegisterUser.cshtml. Press OK.
Thus, we have created our first view. Similarly add one more view UserLogin.cshtml into Views/Login folder and UserHome.cshtml into Views/User folder.
Now, our
Views folder will look like this,
Since our Views have been created, we will put codes in View and Controller for registration and login.
RegisterUser View
This view will be used to register a new user for our application.
Open RegisterUser.cshtml and put following code into it.
- @model CookieAuthDemo.Models.UserDetails
- @{
- ViewData["Title"] = "UserLogin";
- }
- <h2>Register</h2>
- <h4>New User</h4>
- <hr />
- <div class="row">
- <div class="col-md-4">
- @if (TempData["Success"] != null)
- {
- <p class="alert alert-success">@TempData["Success"] <a asp-action="UserLogin">Click here to login</a></p>
- }
- @if (TempData["Fail"] != null)
- {
- <p class="alert alert-danger">@TempData["Fail"]</p>
- }
- <form asp-action="RegisterUser">
- <div asp-validation-summary="ModelOnly" class="text-danger"></div>
- <div class="form-group">
- <label asp-for="FirstName" class="control-label"></label>
- <input asp-for="FirstName" class="form-control" />
- <span asp-validation-for="FirstName" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="LastName" class="control-label"></label>
- <input asp-for="LastName" class="form-control" />
- <span asp-validation-for="LastName" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="UserID" class="control-label"></label>
- <input asp-for="UserID" class="form-control" />
- <span asp-validation-for="UserID" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Password" class="control-label"></label>
- <input asp-for="Password" class="form-control" />
- <span asp-validation-for="Password" class="text-danger"></span>
- </div>
- <div class="form-group">
- <input type="submit" value="Register" class="btn btn-default btn-primary" />
- </div>
- </form>
- </div>
- </div>
- <div>
- <a asp-action="UserLogin">Back to User Login</a>
- </div>
- @section Scripts {
- @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
- }
UserLogin View
This view will hold the Login form and redirects the user to user home page after successful login.
Open UserLogin.cshtml and put the following code into it.
- @model CookieAuthDemo.Models.UserDetails
- @{
- ViewData["Title"] = "UserLogin";
- }
-
- <h2>User</h2>
- <h4>Login</h4>
- <hr />
- <div class="row">
- <div class="col-md-4">
- @if (TempData["UserLoginFailed"] != null)
- {
- <p class="alert alert-danger">@TempData["UserLoginFailed"]</p>
- }
-
- <form asp-action="UserLogin">
- <div asp-validation-summary="ModelOnly" class="text-danger"></div>
- <div class="form-group">
- <label asp-for="UserID" class="control-label"></label>
- <input asp-for="UserID" class="form-control" />
- <span asp-validation-for="UserID" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Password" class="control-label"></label>
- <input asp-for="Password" class="form-control" />
- <span asp-validation-for="Password" class="text-danger"></span>
- </div>
- <div class="form-group">
- <input type="submit" value="Login" class="btn btn-default btn-success" />
- <a asp-action="RegisterUser" class="btn btn-info">SignUp</a>
- </div>
- </form>
- </div>
- </div>
- @section Scripts {
- @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
- }