×

iFour Logo

Explain Forms Authentication in ASP.NET MVC

Kapil Panchal - July 20, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
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.

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.

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.

Login View Code



@model MvcFormAuthentication_Demo.Models.UserModel
@{
    ViewBag.Title = "Login";
}
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Login Form

@Html.LabelFor(m => m.Username) @Html.TextBoxFor(m => m.Username, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Username)
@Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Password)
@Html.ActionLink("New User", "Register")
}

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.


        

Step 9

Similarly, another controller for CRUD operations should be added by right-clicking on the Controllers folder and select Add 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.

 
  

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.

Explain Forms Authentication in ASP.NET MVC Table of Content 1. Introduction 2. Create Employee Table 3. Create Department Table 4. Create Users Table 5.Create UserRoles Table 6. Complete code for HomeController 7. Register View Code 8. Login View Code 9. Use Authorize Attribute 10.Conclusion 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.   How can I sign up or register a new user in our app? Built the User Login Page How to use the built-in Authorize Attribute Adding the logout functionality 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.   In the web.config file, set the authentication mode to Forms. FormsAuthentication.SetAuthCookie is required to use for login. 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". Figure: Create New ASP.NET Web Application Step 4   Then, choose “Empty” and select MVC from the checkbox and then add the project. 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…". 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." 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. Select the EF Designer from the database and then click on the next in the wizard Read More: What Is Exception Filter And Explain Custom Exception Filter In Asp.net Mvc?   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. 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. 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. 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. Figure: Employee Model Step 6 Now right-click the Controllers folder and then choose Add Controller. Figure: Add the New Controller in controller folder There will be a window appear. Click "Add" after selecting MVC5 Controller-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. 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 Figure: Add the view for Register ActionMethod Register View Code   @model MvcFormAuthentication_Demo.Models.UserModel @{ ViewBag.Title = "Register"; } @using (Html.BeginForm()) { @Html.AntiForgeryToken()Register Form @Html.LabelFor(m => m.Username) @Html.TextBoxFor(m => m.Username, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Username) @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Password) Register @Html.ActionLink("Login here", "Login") } Figure: Add the view for Login ActionMethod Login View Code @model MvcFormAuthentication_Demo.Models.UserModel @{ ViewBag.Title = "Login"; } @using (Html.BeginForm()) { @Html.AntiForgeryToken()Login Form @Html.LabelFor(m => m.Username) @Html.TextBoxFor(m => m.Username, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Username) @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Password) Login @Html.ActionLink("New User", "Register") } Looking for Trusted Dot Net Development Company For Your Business? CONNECT US Step 8 Add the following code to the system.web section of the web.config file for forms authentication. Step 9 Similarly, another controller for CRUD operations should be added by right-clicking on the Controllers folder and select Add Controller. Figure: Add the MVC5 controller A new window will open. Click "Add" to add an MVC5 Controller with a view that uses Entity Framework. 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. 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.   @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) @if (User.Identity.IsAuthenticated) {@Html.ActionLink("Employee List", "Index", "Employees", new { @class = "nav-link" }) @Html.ActionLink("Add New Employee", "Create", "Employees", new { @class = "nav-link" })  @User.Identity.Name My Account Edit Profile  @Html.ActionLink("Logout", "Logout", "Home", new { @class = "nav-link text-center text-uppercase" }) } else {@Html.ActionLink("Home", "Index", "Home", new { @class = "nav-link" }) @Html.ActionLink("About", "About", "Home", new { @class = "nav-link" }) @Html.ActionLink("Register", "Register", "Home", new { @class = "nav-link float-left" }) @Html.ActionLink("Login", "Login", "Home", new { @class = "nav-link float-left" }) } 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.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Should I use Node.js 20 for Healthcare application development?
Should I use Node.js 20 for Healthcare application development?

Node.js plays a pivotal role in innovation, reinventing healthcare processes and patient care impeccably with healthcare app development. It has been a top choice for professionals...

How Serverless and Azure Technologies are Reshaping the Healthcare Sector?
How Serverless and Azure Technologies are Reshaping the Healthcare Sector?

Technological advancements are orchestrating a monumental shift in the field of Healthcare software development. The advent of Azure and serverless technologies made an unbelievable impact on the ways of app development and deployment. Today, you can discover a variety of healthcare apps that can assess your healthcare, monitor your body's state, and provide you with helpful suggestions on how to improve it. You may access them at any time and from any location, fundamentally altering the way healthcare is seen.

Top 5 B2B SaaS Tools to Improve Team Communication
Top 5 B2B SaaS Tools to Improve Team Communication

Do you want your workplace to have greater collaboration and teamwork? Staying in touch with coworkers is difficult in this era of remote work. In this changing world, the demand for...