Monday, December 5, 2016

Authentication and Authorization in MVC

Windows authentication or Forms authentication for MVC.

Windows authentication

1. In the web.config, set the authentication mode to Windows.
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization> 

2. In the controller, use authorize attribute which specifies who have access to these controllers and actions.
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
    //
    // GET: /Start/
    [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
    public ActionResult Index()
    {
        return View("MyView");
    }
} 

Forms authentication

1. In the web.config, set the authentication mode to Forms and the login URL points to a controller.
<authentication mode="Forms">
<forms loginUrl="~/Home/Login"  timeout="2880"/>
</authentication> 

2. In the controller, check valid user access and set in cookie.
public ActionResult Login()
{
    if ((Request.Form["txtUserName"] == "Shiv") && 
          (Request.Form["txtPassword"] == "Shiv@123"))
    {
        FormsAuthentication.SetAuthCookie("Shiv",true);
        return View("About");
    }
    else
    {
        return View("Index");
    }
} 

3.All Authorize attribute to all pages so any unauthorized user making a call to these controllers will be redirected to the controller (in this case the controller is “Login”) .

[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
} 

No comments:

Post a Comment