Security in MVC4






Traditional security in web applications has focused on securing a file or folder through web.config. The problem with this security model is that a path is unreliable when using routing. Two different routes can lead to the same function and thus both routes need to be secured. This opens up for security holes.

When looking at security it’s important to consider what it is you need to secure. In MVC it’s the controller – the heart of the functionality.

The recommended approach for MVC2 was to use the Authorize attribute to secure your controller and/or its functions. The downside with this way is that if you forget to add the attribute you have a security problem.

In MVC3 the recommended approach was to use global filters instead.

public sealed class LogonAuthorize : AuthorizeAttribute
{
  public override void OnAuthorization(AuthorizationContext filterContext)
  {
    bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
    if (!skipAuthorization)
    {
      base.OnAuthorization(filterContext);
    }
  }
}

In MVC4 this functionality is implemented from start and you can secure your whole application by adding the AuthorizeAttribute as a filter and then just opt out with [AllowAnonymous] on the controllers and/or functions that anonymous users can use.

public class FilterConfig
{
  public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  {
    filters.Add(new HandleErrorAttribute());
    filters.Add(new RequireHttpsAttribute());
    filters.Add(new AuthorizeAttribute());
  }
}