Forms authentication is implemented the same way as in ASP.NET. The first step is to set the authentication mode equal to Forms
. The loginUrl
points to a controller here rather than a page.
<authentication mode="Forms">
<forms loginUrl="~/Home/Login" timeout="2880"/>
</authentication>
We also need to create a controller where we will check if the user is proper or not. If the user is proper we will set the cookie value.
public ActionResult Login()
{
if ((Request.Form["txtUserName"] == "Shiv") &&
(Request.Form["txtPassword"] == "Shiv@123"))
{
FormsAuthentication.SetAuthCookie("Shiv",true);
return View("About");
}
else
{
return View("Index");
}
}
All the other actions need to be attributed with the Authorize
attribute so that any unauthorized user making a call to these controllers will be redirected to the controller (in this case the controller is “Login”) which will do the authentication.
[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
}