Monday, January 7, 2013

Using ActionFilters to prevent unauthorized access

In this post I am going to create an ActionFilter for my ASP.NET MVC website that checks if the user is authenticated before accessing a page.

First I have to create a class that will inherit from ActionFilterAttribute:
public class MyAuthClass: ActionFilterAttribute

Inside the class we override the method OnActionExecuting (is called before an action of a controller is executed):

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string controllerName = filterContext.Controller.GetType().Name;

            //the only controller that doesn't need authentication is the Login Controller
            if (!controllerName.Equals("LoginController"))
            {
             

                bool IsAuth = false;

                IsAuth = true; //Normally here you must implement some logic that checks if the login succeeded or not.

                if (!IsAuth) //not authenticated, send it back to the login page
                {
                    RouteValueDictionary redirectDict = new RouteValueDictionary();
                    redirectDict.Add("action", "Login");
                    redirectDict.Add("controller", "Login");

                    filterContext.Result = new RedirectToRouteResult(redirectDict);
                }
            }
           
        }

In order for the ActionFilter to work we need to write above the Controller declaration the following:


[MyProject.ActionFilters.MyAuthClass] 
 public class BaseController : Controller
    {
     //some code goes here;
      }

 

For a better understanding of Action Filters in MVC follow this tutorial: http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/understanding-action-filters-cs

No comments:

Post a Comment