Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc 3 session and authorizeAttribute

My site is open to all but i have a controller with some method that only the manager with the user and password can enter. I'm saving the bool IsManager in a session.
I would like to use the authorize attribute to block whom ever IsManager == false.

like image 509
mashta gidi Avatar asked Jan 17 '23 03:01

mashta gidi


1 Answers

First define an ActionFilter:

public class TheFilter: ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
        var session = filterContext.HttpContext.Session;
        if ((bool?)session["IsManager"] == true)
            return;

        //Redirect him to somewhere.
        var redirectTarget = new RouteValueDictionary
             {{"action", "{ActionName}"}, {"controller", "{ControllerName}"}};
        filterContext.Result = new RedirectToRouteResult(redirectTarget);
   }
}

Then use it above the restricted Action(or controller):

//[TheFilter]
public class ManagersController : Controller
{
    [TheFilter]
    public ActionResult Foo()
    {
        ...
        return View();
    }
}
like image 119
gdoron is supporting Monica Avatar answered Jan 26 '23 00:01

gdoron is supporting Monica