Asp.Net MVC4 AllowAnonymous

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!

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.