ASP.NET MVC Authentication by redirection to the login page and then back
I have an ASP.NET MVC web site. I have many actions which require authentication to be performed. So, I need the user to get redirected to the login page, and after login (if successful) to be redirected back. So wh开发者_Go百科at I want to do now is to build a new class, smth. kind of seen below:
class AuthChecker
{
public AuthChecker(string authActionName, string authControllerName)
{
//...
}
public ActionResult InvokeIfAuthenticated(Func<ActionResult> body, string errorNoAuth, string returnUrl)
{
if (Request.IsAuthenticated)
{
return body();
}
else
{
//set returnUrl and return RedirectToAction(authAction);
}
}
}
So is that okay, or there is some out-of-box solution to manage this situation? Or maybe there is some better solution?
You're looking for the Authorize
attribute.
For example [from the link below]:
[Authorize]
public ActionResult AuthenticatedUsers()
{
return View();
}
[Authorize(Roles = "Admin, Super User")]
public ActionResult AdministratorsOnly()
{
return View();
}
[Authorize(Users = "Betty, Johnny")]
public ActionResult SpecificUserOnly()
{
return View();
}
Restrict Access to an Action Method
精彩评论