How do you implement Forms authentication in MVC?

Answer

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();
} 

All asp.net-mvc Questions

Ask your interview questions on asp-net-mvc

Write Your comment or Questions if you want the answers on asp-net-mvc from asp-net-mvc Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---