Forms Authentication In MVC

Introduction

Whenever we develop a web application three things are common there - Sign up, Sign in, and Log out. As part of this article, we are going to discuss the following things in detail.
  1. How to Sign up a new user into our application
  2. Implementing the User Login page.
  3. How to use the built-in Authorize Attribute
  4. Implementing the logout functionality
  5. How to use Forms Authentication in MVC application to achieve all the above points
I will discuss MVC application security in upcoming articles. Forms Authentication is available in System.Web.Security namespace. In order to implement the Forms Authentication in MVC application, we need to do the following three things.
  1. Set the Authentication mode as Forms in the web.config file
  2. We need to use FormsAuthentication.SetAuthCookie for login
  3. Again we need to use FormAuthentication.SignOut for logout
Step 1
 
Open your favorite SQL Server database with any version. It really doesn’t matter what version it is. I am using SQL Server 2017 for this article.
 
Create EMPLOYEE TABLE 
  1. CREATE TABLE [dbo].[Employee](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [nvarchar](50) NULL,  
  4.     [Gender] [char](10) NULL,  
  5.     [Age] [intNULL,  
  6.     [Position] [nvarchar](50) NULL,  
  7.     [Office] [nvarchar](50) NULL,  
  8.     [HireDate] [datetime] NULL,  
  9.     [Salary] [intNULL,  
  10.     [DepartmentId] [intNULL,  
  11. PRIMARY KEY CLUSTERED   
  12. (  
  13.     [Id] ASC  
  14. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  15. ON [PRIMARY]  
  16. GO  
  17.   
  18. ALTER TABLE [dbo].[Employee]  WITH CHECK ADD FOREIGN KEY([DepartmentId])  
  19. REFERENCES [dbo].[Department] ([Id])  
  20. GO  
Create Department Table
  1. CREATE TABLE [dbo].[Department](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [DepartmentName] [nvarchar](50) NULL,  
  4. PRIMARY KEY CLUSTERED   
  5. (  
  6.     [Id] ASC  
  7. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  8. ON [PRIMARY]  
  9. GO  
Create Users Table
  1. CREATE TABLE [dbo].[Users](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Username] [nvarchar](50) NULL,  
  4.     [Password] [nvarchar](50) NULL,  
  5. PRIMARY KEY CLUSTERED   
  6. (  
  7.     [Id] ASC  
  8. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  9. ON [PRIMARY]  
  10. GO  
Create Roles Table
  1. CREATE TABLE [dbo].[Roles](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [RoleName] [nvarchar](50) NULL,  
  4. PRIMARY KEY CLUSTERED   
  5. (  
  6.     [Id] ASC  
  7. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  8. ON [PRIMARY]  
  9. GO  
Create UserRolsMapping Table
  1. CREATE TABLE [dbo].[UserRolesMapping](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [UserId] [intNULL,  
  4.     [RoleId] [intNULL,  
  5. PRIMARY KEY CLUSTERED   
  6. (  
  7.     [Id] ASC  
  8. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  9. ON [PRIMARY]  
  10. GO  
  11.   
  12. ALTER TABLE [dbo].[UserRolesMapping]  WITH CHECK ADD FOREIGN KEY([RoleId])  
  13. REFERENCES [dbo].[Roles] ([Id])  
  14. GO  
  15.   
  16. ALTER TABLE [dbo].[UserRolesMapping]  WITH CHECK ADD FOREIGN KEY([RoleId])  
  17. REFERENCES [dbo].[Roles] ([Id])  
  18. GO  
  19.   
  20. ALTER TABLE [dbo].[UserRolesMapping]  WITH CHECK ADD FOREIGN KEY([UserId])  
  21. REFERENCES [dbo].[Users] ([Id])  
  22. GO  
Step-2
 
Open Visual Studio 2019 or an editor of your choice and create a new project.
 
Step 3
 
Choose the "web application" project and give an appropriate name to your project. Click on "Create".
 
Forms Authentication In MVC
 
Step 4
 
Select the "empty" template, check on MVC checkbox and click Create.
 
Forms Authentication In MVC
 
Step 5
 
Right-click the Models folder and add a database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select "New Item".
 
Forms Authentication In MVC
 
You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name EmployeeModel (this name is not mandatory, you can give any name) and click "Add".
 
Forms Authentication In MVC
 
After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".
 
Forms Authentication In MVC
 
After clicking on "Next", a window will appear. Choose "New Connection". Another window will appear. Add your server name - if it is local, then enter a dot (.). Choose your database and click "OK".
 
Forms Authentication In MVC
 
The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next".
 
Forms Authentication In MVC
 
After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".
 
Forms Authentication In MVC
 
Entity Framework gets added and the respective class gets generated under the Models folder.
 
Forms Authentication In MVC
 
Step 6
 
Right-click on Controllers folder and add a controller.
 
Forms Authentication In MVC
 
A window will appear. Choose MVC5 Controller-Empty and click "Add".
 
Forms Authentication In MVC
 
After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home
 
Forms Authentication In MVC
 
Step 7
 
Right-click on the Index method in HomeController; the "Add View" window will appear with the default index name checked (use a Layout page). Click on "Add".
 
Complete code for HomeController 
  1. using MvcFormAuthentication_Demo.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. using System.Web.Security;  
  8.   
  9. namespace MvcFormAuthentication_Demo.Controllers  
  10. {  
  11.       
  12.     public class HomeController : Controller  
  13.     {  
  14.         private readonly EmployeeContext _dbContext = new EmployeeContext();  
  15.         public ActionResult Index()  
  16.         {  
  17.             return View();  
  18.         }  
  19.         public ActionResult Login()  
  20.         {  
  21.             return View();  
  22.         }  
  23.         [HttpPost]  
  24.         [ValidateAntiForgeryToken]  
  25.         public ActionResult Login(UserModel user)  
  26.         {  
  27.             if (ModelState.IsValid)  
  28.             {  
  29.                 bool IsValidUser = _dbContext.Users  
  30.                .Any(u => u.Username.ToLower() == user  
  31.                .Username.ToLower() && user  
  32.                .Password == user.Password);  
  33.   
  34.                 if (IsValidUser)  
  35.                 {  
  36.                     FormsAuthentication.SetAuthCookie(user.Username, false);  
  37.                     return RedirectToAction("Index""Employee");  
  38.                 }  
  39.             }  
  40.             ModelState.AddModelError("""invalid Username or Password");  
  41.             return View();  
  42.         }  
  43.         public ActionResult Register()  
  44.         {  
  45.             return View();  
  46.         }  
  47.         [HttpPost]  
  48.         [ValidateAntiForgeryToken]  
  49.         public ActionResult Register(User registerUser)  
  50.         {  
  51.             if (ModelState.IsValid)  
  52.             {  
  53.                 _dbContext.Users.Add(registerUser);  
  54.                 _dbContext.SaveChanges();  
  55.                 return RedirectToAction("Login");  
  56.   
  57.             }  
  58.             return View();  
  59.         }  
  60.         public ActionResult Logout()  
  61.         {  
  62.             FormsAuthentication.SignOut();  
  63.             return RedirectToAction("Login");  
  64.         }  
  65.     }  
  66. }  
Add two views, one for registering and a second for login
 
Forms Authentication In MVC
 
Register View Code 
  1. @model MvcFormAuthentication_Demo.Models.User  
  2. @{  
  3.     ViewBag.Title = "Register";  
  4. }  
  5.   
  6. @using (Html.BeginForm())  
  7. {  
  8.     @Html.AntiForgeryToken()  
  9.     <div class="card custom-card">  
  10.         <div class="card-header bg-primary text-white">  
  11.             <h3>Register Form</h3>  
  12.         </div>  
  13.         <div class="card-body">  
  14.             <div class="form-group">  
  15.                 @Html.LabelFor(m => m.Username)  
  16.                 @Html.TextBoxFor(m => m.Username, new { @class = "form-control" })  
  17.                 @Html.ValidationMessageFor(m => m.Username)  
  18.             </div>  
  19.             <div class="form-group">  
  20.                 @Html.LabelFor(m => m.Password)  
  21.                 @Html.PasswordFor(m => m.Password, new { @class = "form-control" })  
  22.                 @Html.ValidationMessageFor(m => m.Password)  
  23.             </div>  
  24.             <div class="form-group">  
  25.                 <button type="submit" class="btn btn-primary rounded-0">Register</button>  
  26.                 @Html.ActionLink("Login here""Login")  
  27.             </div>  
  28.   
  29.         </div>  
  30.     </div>  
  31. }  
Forms Authentication In MVC
 
Login View code
  1. @model MvcFormAuthentication_Demo.Models.UserModel  
  2. @{  
  3.     ViewBag.Title = "Login";  
  4. }  
  5.   
  6. @using (Html.BeginForm())  
  7. {  
  8.     @Html.AntiForgeryToken()  
  9.     <div class="card custom-card">  
  10.         <div class="card-header bg-primary text-white">  
  11.             <h3>Login Form</h3>  
  12.         </div>  
  13.         <div class="card-body">  
  14.             <div class="form-group">  
  15.                 @Html.LabelFor(m=>m.Username)  
  16.                 @Html.TextBoxFor(m => m.Username, new { @class = "form-control" })  
  17.                 @Html.ValidationMessageFor(m => m.Username)  
  18.             </div>  
  19.             <div class="form-group">  
  20.                 @Html.LabelFor(m => m.Password)  
  21.                 @Html.PasswordFor(m => m.Password, new { @class = "form-control" })  
  22.                 @Html.ValidationMessageFor(m => m.Password)  
  23.             </div>  
  24.             <div class="form-group">  
  25.                 <button type="submit" class="btn btn-primary rounded-0">Login</button>  
  26.                 @Html.ActionLink("New User","Register")  
  27.             </div>  
  28.              
  29.         </div>  
  30.     </div>  
  31. }  
Step 8
 
Open web.config and Add following code for forms authentication
  1. <authentication mode="Forms">  
  2.   <forms loginUrl="Home/Login"></forms>  
  3. </authentication>  
Step 9
 
Similarly, add another controller for CRUD operation. Right-click on the Controllers folder and add a controller.
 
Forms Authentication In MVC
 
A window will appear. Choose MVC5 Controller with a view, using Entity Framework and click "Add".
 
Forms Authentication In MVC
 
After clicking on "Add", another window will appear. Choose a model class and database context class, click on Add. It will generate the respective view with the controller - create, edit, update, and delete code and views.
 
Forms Authentication In MVC
 
Use Authorize Attribute
  1. [Authorize]  
  2. public class EmployeesController : Controller  
  3. {  
  4. }  
The Authorize Attribute is the built-in attribute provided by MVC which is basically used to authenticate a user.  Decorate the action methods which you don’t want any anonymous user to access with Authorize Attribute.
 
Step 10
 
Open _Layout file and modify it with the following code. 
  1. <nav class="navbar navbar-expand-lg navbar-light bg-light">  
  2.     <a class="navbar-brand" href="#">  
  3.         @Html.ActionLink("Application name""Index""Home"new { area = "" }, new { @class = "navbar-brand" })  
  4.     </a>  
  5.     <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">  
  6.         <span class="navbar-toggler-icon"></span>  
  7.     </button>  
  8.     <div class="collapse navbar-collapse" id="collapsibleNavbar">  
  9.         <ul class="navbar-nav">  
  10.             @if (User.Identity.IsAuthenticated)  
  11.             {  
  12.                 <li>@Html.ActionLink("Employee List""Index""Employees"new { @class = "nav-link" })</li>  
  13.                 <li>@Html.ActionLink("Add New Employee""Create""Employees"new { @class = "nav-link" })</li>  
  14.                 <li class="nav-item dropdown">  
  15.                     <a class="nav-link dropdown-toggle text-center text-uppercase" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">  
  16.                         @User.Identity.Name  
  17.                     </a>  
  18.                     <div class="dropdown-menu" aria-labelledby="navbarDropdown">  
  19.                         <a class="dropdown-item" href="#">My Account</a>  
  20.                         <a class="dropdown-item" href="#">Edit Profile</a>  
  21.                         <div class="dropdown-divider"></div>  
  22.                         @Html.ActionLink("Logout""Logout""Home"new { @class = "nav-link text-center text-uppercase" })  
  23.                     </div>  
  24.                 </li>  
  25.             }  
  26.             else  
  27.             {  
  28.                 <li>@Html.ActionLink("Home""Index""Home"new { @class = "nav-link" })</li>  
  29.                 <li>@Html.ActionLink("About""About""Home"new { @class = "nav-link" })</li>  
  30.                 <li>@Html.ActionLink("Register""Register""Home"new { @class = "nav-link float-left" })</li>  
  31.                 <li>@Html.ActionLink("Login""Login""Home"new { @class = "nav-link float-left" })</li>  
  32.   
  33.             }  
  34.         </ul>  
  35.     </div>  
  36. </nav>  
Step 11
 
Build and run your application ctrl+F5

Output Screens

 
Register Form
 
Forms Authentication In MVC
 
Login Form
 
Forms Authentication In MVC
 
Employee List
 
Forms Authentication In MVC
 
Add New Employee
 
Forms Authentication In MVC
 
Edit Employee
 
Forms Authentication In MVC
 
Employee Details
 
Forms Authentication In MVC
 
Delete Employee
 
Forms Authentication In MVC


Similar Articles