You can use Windows or Forms authentication for MVC.
How to implement Windows authentication for MVC?
For Windows authentication you need to modify the web.config file and set the authentication mode to Windows.
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>
Then in the controller or on the action, you can use the
Authorize
attribute which specifies which users have access to these controllers and actions. Below is the code snippet for that. Now only the users specified in the controller and action can access it.[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
//
// GET: /Start/
[Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
public ActionResult Index()
{
return View("MyView");
}
}
How do you implement Forms authentication in MVC?
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();
}
No comments:
Post a Comment