views:

55

answers:

1

Hi there. I have an ASP.NET MVC web site. I have many actions which require authentification 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 what 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?

Thanks in advance.

+5  A: 

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

Jack Marchetti