How to implement Forms Authentication in MVC?

Working of Forms Authentication.

1.The user tries to send a  request to Forms authentication enabled application through a browser.
2. The browser sends all the associated cookies stored in the client machine with request.
3. When request is received as server end, server examines the request and check for the special cookie called “Authentication Cookie”.
4.If valid authentication cookie is found, server confirms the identity of the user or in simple words, consider user as a valid user and make him go further.
5. If valid authentication cookie is not found server considers user as anonymous (or unauthenticated) user. In this case if the requested resource is marked as protected/secured user will be redirected to login page.

To start implementing Forms Authentication, we will first create a Controller. Let us call it AuthenticationController.

In the Controller create a method called Login.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCOne.Controllers
{
public class AuthenticationController : Controller
{
// GET: Authentication
public ActionResult Login()
{
return View();
}
}
}

Create a Models class called UserDetails

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCOne.Models
{
public class UserDetails
{
public string UserName { get; set; }
public string Password { get; set; }
}
}

Create a LoginView with UserDetails as the Model.
Write the following code in the View.

@model MVCOne.Models.UserDetails

@{
Layout = null;
}

<!DOCTYPE html>
<html>
<head>
<meta name="Viewport" content="width =device-width" />
<title>Login</title>
</head>
<body>
<div> @using (Html.BeginForm("DoLogin", "Authentication", FormMethod.Post))
{@Html.LabelFor(c => c.UserName) @Html.TextBoxFor(x => x.UserName) <br /> @Html.LabelFor(c => c.Password) @Html.PasswordFor(x => x.Password) <br /> <input type="submit" name="BtnSubmit" value="Login" />} </div>
</body>
</html>

 

This is the generated html

 

 

<!DOCTYPE html>
<html>
<head>
<meta name="Viewport" content="width =device-width" />
<title>Login</title>
</head>
<body>
<div> <form action="/Authentication/DoLogin" method="post"><label for="UserName">UserName</label><input id="UserName" name="UserName" type="text" value="" /> <br /> <label for="Password">Password</label><input id="Password" name="Password" type="password" /> <br /> <input type="submit" name="BtnSubmit" value="Login" /></form> </div>
</body>
</html>

 

Now, add the following code to Web.config

<system.web>
<authentication mode="Forms"> <forms loginUrl="~/Authentication/Login"></forms>
</authentication>

 

<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>

Any unauthenticated user will be redirected to Authentication/Login.

Now open a Controller, ChampakController and write [Authorize] before the index method.

public class ChampakController : Controller
{
public ActionResult Razor()
{
Book b = new Book();
b.BookId = 10;
b.BookName = "Basic Java";
b.Price = 1200;
b.IsAvailable = true;
b.BookType="Text Book";
b.Topics = new string[] {"Threads","Arrays","Web" };
return View(b);
}
[Authorize]
 public ActionResult Index()
 {
 return View();
 }
public ActionResult Del(int id=0)
{
try
{
BooksSupplier supplier = new BooksSupplier();
Book book = supplier.Books.Find(id);

View the Index.cshtml file under the Champak View and see the result.
The User is redirected to the http://localhost:49455/Authentication/Login location and the URL in the address bar shows.
http://localhost:49455/Authentication/Login?ReturnUrl=%2fChampak%2fIndex
The user will be transported to the ReturnUrl on successful login.

Now, create a DoLogin method in the AuthenticationController.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCOne.Models;
namespace MVCOne.Controllers
{
public class AuthenticationController : Controller
{
// GET: Authentication
public ActionResult Login()
{
return View();
}
[HttpPost]
 public ActionResult DoLogin(UserDetails details)
 {
 if(details.UserName.Equals("Pappu") && details.Password.Equals("Pass"))
 {
 System.Web.Security.FormsAuthentication.SetAuthCookie(details.UserName, false);
 return RedirectToAction("Index", "Champak"); } 
 else
 {
 ModelState.AddModelError("LoginError", "Invalid Username or Password");
 return View("Login");
 }

 

}
 }

}

For the moment we are assuming that there is only correct username pair(Pappu,Pass). The DoLogin Method will check the credentials and transfer to the Index action in ChampakController.
The System.Web.Security.FormsAuthentication.SetAuthCookie(details.UserName, false); adds a cookie with the username of the current user. The second parameter contains a setting for persistent cookie. The value true will make it a persistent cookie where the login will be maintained across browser restarts, false works only till the browser is closed.
If authentication fails we add an error to the ModelState and display in the LoginView.

@model MVCOne.Models.UserDetails

@{
Layout = null;
}

<!DOCTYPE html>
<html>
<head>
<meta name="Viewport" content="width =device-width" />
<title>Login</title>
</head>
<body>
<div>
@Html.ValidationMessage("LoginError", new { style ="color: red;"})

@using (Html.BeginForm("DoLogin", "Authentication", FormMethod.Post))
{@Html.LabelFor(c => c.UserName) @Html.TextBoxFor(x => x.UserName) <br /> @Html.LabelFor(c => c.Password) @Html.PasswordFor(x => x.Password) <br /> <input type="submit" name="BtnSubmit" value="Login" />}
</div>
</body>
</html>

Now, we display the name of the current user in the browser.
Here is Index View in ChampakController.

 

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<h1>Current User is @User.Identity.Name</h1>
<a href="/Champak/Book/">Book</a>
<br />
<a href="/Champak/Del/">Del</a>
<br />
<a href="/Champak/Update/">Update</a>
</div>
</body>
</html>

 

Leave a Reply