Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Asp.Net MVC4 AllowAnonymous

Posted on: 2012-10-17

In Asp.Net MVC3 and before, if we wanted to make my default all action of controller to be secured we had to create a AllowAnonymous filter and to add a global filter which was requiring a valid authentification before accessing the action.

With Asp.Net MVC 4, it's built in. You need to go inside the App_Start folder which contain the FilterConfig.cs file. Inside the FilterConfig.cs you will found what was inside the Global.Asax.cs : the static method RegisterGlobalFilters.

You need to add to this method the new folder called "AuthorizeAttribute".

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

By now, all action require a valid authentification. If you want to allow anonymous person to see the action, you need to add the AllowAuthorize attribute to the action. In fact, it's already been setup for the login and register method of the AccountController.cs.

[AllowAnonymous] 
public ActionResult Login(string returnUrl) { 
  ViewBag.ReturnUrl = returnUrl; 
  return View(); 
}

[AllowAnonymous] 
public ActionResult Register() { 
  return View(); 
} 

That's it. Pretty simple and more secure!