Sunday, 23 April 2023

Explain Forms Authentication in ASP.NET MVC

 

Explain Forms Authentication in ASP.NET MVC

Introduction


Sign up, sign in, and Log out are three things that we always have in mind while developing a web application. The following points will be discussed in depth as part of this.

 
  1. How can I sign up or register a new user in our app?
  2. Built the User Login Page
  3. How to use the built-in Authorize Attribute
  4. Adding the logout functionality
  5. How to utilize Forms Authentication in an MVC application to accomplish all of the above goals?

The following three steps are required to implement Forms Authentication in an MVC application.

 
  1. In the web.config file, set the authentication mode to Forms.
  2. FormsAuthentication.SetAuthCookie is required to use for login.
  3. Again FormAuthentication.SignOut is required to use for logout.
Step 1

Open any version of your SQL Server database and it makes no difference which version you have.

Create Employee Table


CREATE TABLE [dbo].[Department](
[Id] [int] IDENTITY(1,1) NOT NULL,
[DepartmentName] [nvarchar](50) NULL,
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 Department Table


CREATE TABLE [dbo].[Users](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Username] [nvarchar](50) NULL,
[Password] [nvarchar](50) NULL,
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 Users Table


CREATE TABLE [dbo].[Users](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Username] [nvarchar](50) NULL,
[Password] [nvarchar](50) NULL,
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 Users Table

 

CREATE TABLE [dbo].[UserRolesMapping](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserId] [int] NULL,
[RoleId] [int] NULL,
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 UserRoles Table


CREATE TABLE [dbo].[UserRolesMapping](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserId] [int] NULL,
[RoleId] [int] NULL,
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
ALTER TABLE [dbo].[UserRolesMapping] WITH CHECK ADD FOREIGN KEY([RoleId])
REFERENCES [dbo].[Roles] ([Id])
GO
ALTER TABLE [dbo].[UserRolesMapping] WITH CHECK ADD FOREIGN KEY([RoleId])
REFERENCES [dbo].[Roles] ([Id])
GO
ALTER TABLE [dbo].[UserRolesMapping] WITH CHECK ADD FOREIGN KEY([UserId])
REFERENCES [dbo].[Users] ([Id])
GO

Step 2


Make a new project with Visual Studio 2019 or another editor of your choice.

Step 3


Choose the "ASP.NET web application" project and give an appropriate name to your project and then click on "Create".
CreateNewASPNET
Figure: Create New ASP.NET Web Application

Step 4

 

Then, choose “Empty” and select MVC from the checkbox and then add the project.

createtheEmptyproject
Figure: create the Empty project after a click on the Mvc checkbox

Step 5

Add a database model by right-clicking the Models folder. Now, add the Entity Framework and for that, you have to right-click on the Models folder and then choose "New item…".

Modelfolder
Figure: add the new item in the Model folder of the project

You will be presented with a window; from there, pick Data from the left panel and select ADO.NET Entity Data Model, name it EmployeeModel (this name is not required; any name will suffice), and click "Add."

ADO.NETEntityData
Figure: Select the ADO.NET Entity Data Model and Give the name to that Model

The wizard will open after you click "Add a window." Click "Next" after selecting EF Designer from the database.

EFDesigner
Select the EF Designer from the database and then click on the next in the wizard
 

A window will display after clicking on "Next".Select "New Connection.". After that, a new window will open. Enter your server's name, followed by a dot if it's a local server (.). Click "OK" after selecting your database.

ConnectionProperties
Figure: Connection Properties with server name and database name

The connection will be established. Save the connection name as you wish. Below is where you can modify the name of your connection. The connection will be saved in the web configuration. Now click on the "Next" button.

ModelwizARD
Figure: Entity Data Model wizARD with newly connected FormAuthFDb database

A new window will display after you click NEXT. Click "Finish" after selecting the database table name as seen in the screenshot below.

Createdatabase
Figure: Database table of your created database in SQL Server

Now, Entity Framework is added, and a class is created for each entity in the Models folder.

EmployeeModel
Figure: Employee Model

Step 6

Now right-click the Controllers folder and then choose Add Controller.

Controllerincontroller
Figure: Add the New Controller in controller folder

There will be a window appear. Click "Add" after selecting MVC5 Controller-Empty.

MVC5Controller-Empty
Figure: select MVC5 Controller-Empty from the controller

After selecting "Add," a new window with the name DefaultController will appear. Then change the name to the controller HomeController and then click on Add.

HomeController
Figure: change the name of the controller to “HomeController”

Step 7

When you right-click on the Index method in HomeController, the "Add View" dialogue will pop up, with the default index name selected (use a Layout page), and after that select the "Add" button to add a view for the index method.

Complete code for HomeController


using MvcFormAuthentication_Demo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace MvcFormAuthentication_Demo.Controllers
{
public class HomeController : Controller
{
private readonly FormAuthDbEntities _dbContext = new FormAuthDbEntities();
public ActionResult Index()
{
return View();
}
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserModel user)
{
if (ModelState.IsValid)
{
bool IsValidUser = _dbContext.Users
.Any(u => u.Username.ToLower() == user
.Username.ToLower() && user
.Password == user.Password);
if (IsValidUser)
{
FormsAuthentication.SetAuthCookie(user.Username, false);
return RedirectToAction("Index", "Employee");
}
}
ModelState.AddModelError("", "invalid Username or Password");
return View();
}
public ActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(User registerUser)
{
if (ModelState.IsValid)
{
_dbContext.Users.Add(registerUser);
_dbContext.SaveChanges();
return RedirectToAction("Login");
}
return View();
}
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login");
}
}
}

Create two views, one for registration and the other for login.

Register View Code


ActionMethod
Figure: Add the view for Register ActionMethod

Register View Code

 
@model MvcFormAuthentication_Demo.Models.UserModel
@{
ViewBag.Title = "Register";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()<div class="card custom-card"><div class="card-header bg-primary text-white"><h3>Register Form</h3></div>
<div class="card-body"><div class="form-group">
@Html.LabelFor(m => m.Username)
@Html.TextBoxFor(m => m.Username, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Username)</div>
<div class="form-group">
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password)</div>
<div class="form-group"><button class="btn btn-primary rounded-0" type="submit">Register</button>
@Html.ActionLink("Login here", "Login")</div></div></div>
}
LoginActionMethod
Figure: Add the view for Login ActionMethod

Login View Code


@model MvcFormAuthentication_Demo.Models.UserModel
@{
ViewBag.Title = "Login";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()<div class="card custom-card"><div class="card-header bg-primary text-white"><h3>Login Form</h3></div>
<div class="card-body"><div class="form-group">
@Html.LabelFor(m => m.Username)
@Html.TextBoxFor(m => m.Username, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Username)</div>
<div class="form-group">
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password)</div>
<div class="form-group"><button class="btn btn-primary rounded-0" type="submit">Login</button>
@Html.ActionLink("New User", "Register")</div></div></div>
}

Looking for Trusted Dot Net Development Company For Your Business?


Step 8

Add the following code to the system.web section of the web.config file for forms authentication.

<authentication mode="Forms">
<forms loginurl="Home/Login"></forms>
</authentication>
Step 9

Similarly, another controller for CRUD operations should be added by right-clicking on the Controllers folder and select Add Controller.

theMVC5controller
Figure: Add the MVC5 controller

A new window will open. Click "Add" to add an MVC5 Controller with a view that uses Entity Framework.

usingEntityFramework
Figure: Select MVC5 Controller with views, using Entity Framework

A new window will display after clicking on "Add", Select a model class and a database context class, and then click on Add. It will create the respective views with the controller - create, edit, update, and delete code and views.

classandDatacontext
Figure: Select Model class and Data context for the controller

Use Authorize Attribute


[Authorize]
public class EmployeesController : Controller
{
}

The Authorize Attribute is a built-in MVC attribute that is used to authenticate a user.Use the Authorize Attribute to protect the action methods that you don't want anonymous users to see.


Step 10

Example

Modify the _Layout.cshtml file with the following code.

 
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</a><button aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarSupportedContent" data-toggle="collapse" type="button"></button>
<div class="collapse navbar-collapse" id="collapsibleNavbar"><ul class="navbar-nav"><li>
@if (User.Identity.IsAuthenticated)
{</li><li>@Html.ActionLink("Employee List", "Index", "Employees", new { @class = "nav-link" })</li><li> </li><li>@Html.ActionLink("Add New Employee", "Create", "Employees", new { @class = "nav-link" })</li><li> </li><li class="nav-item dropdown">
<a aria-expanded="false" aria-haspopup="true" class="nav-link dropdown-toggle text-center text-uppercase" data-toggle="dropdown" href="#" id="navbarDropdown" role="button">
@User.Identity.Name
</a><div aria-labelledby="navbarDropdown" class="dropdown-menu">
<a class="dropdown-item" href="#">My Account</a>
<a class="dropdown-item" href="#">Edit Profile</a><div class="dropdown-divider"> </div>
@Html.ActionLink("Logout", "Logout", "Home", new { @class = "nav-link text-center text-uppercase" })</div></li><li>
}
else
{</li><li>@Html.ActionLink("Home", "Index", "Home", new { @class = "nav-link" })</li><li> </li><li>@Html.ActionLink("About", "About", "Home", new { @class = "nav-link" })</li><li> </li><li>@Html.ActionLink("Register", "Register", "Home", new { @class = "nav-link float-left" })</li><li> </li><li>@Html.ActionLink("Login", "Login", "Home", new { @class = "nav-link float-left" })</li><li>
}</li></ul></div></nav>
Step 11.

Build and run your ASP.net web application with ctrl + F5


Conclusion

In this blog, we learned forms authentication in the Asp.Net web application with an example. It will effectively help in comprehending the essentiality of authentication.

Content source:  https://www.ifourtechnolab.com/blog/explain-forms-authentication-in-asp-net-mvc



No comments:

Post a Comment

PowerApps Consulting Services - Driving Innovation in Enterprise Solutions

Driving innovation while keeping costs in check is something that every executive looks for. Microsoft Power Apps is a leading low-code app ...