Exclude some actions from Authorize in ASP.net MVC

Putting the [Authorize] attribute on the controller is basically a shortcut to putting it on every action, so your code is logically equivalent to

// No [Authorize] here
public class TestController : Controller
{
    [Authorize]
    public ActionResult Index()
    {
         // code here...
    }

    [Authorize]
    public ActionResult Test()
    {
         // code here...
    }
}

You can probably see where I'm going with this - remove the attribute from the controller, and put it on the specific actions that you want to be restricted:

// No [Authorize] here
public class TestController : Controller
{
    [Authorize]
    public ActionResult Index()
    {
         // code here...
    }

    // no [Authorize] here either, so anonymous users can access it...
    public ActionResult Test()
    {
         // code here...
    }
}

You can take the approach outlined in this blog post of creating an AllowAnonymous attribute and placing this attribute on actions you wish to exclude:

http://blogs.msdn.com/b/rickandy/archive/2011/05/02/securing-your-asp-net-mvc-3-application.aspx

As of MVC 4, the AllowAnonymous attribute is stock and can be applied as needed.


You might want to put the attribute on top of the restricted actions and leave the others (the ones in which you want to allow anonymous access) alone.

Also take it out of the top of the class.