Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude some actions from Authorize in ASP.net MVC

There is an authorize attribute on top of my contoller that means it contains all of my actions. I want to exclude some actions from this attribute (these actions be available by anonymous users). Is it possible?

[Authorize]
public class TestController : Controller
{
   public ActionResult Index()
   {
     ...
   }
   ...

   //available by anonymous
   public ActionResult Test()
   {
     ...
   }
}
like image 531
Ghooti Farangi Avatar asked Jul 14 '11 06:07

Ghooti Farangi


3 Answers

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.

like image 87
Joe Cartano Avatar answered Nov 07 '22 11:11

Joe Cartano


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...
    }
}
like image 37
Jon Avatar answered Nov 07 '22 11:11

Jon


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.

like image 4
Kenji Kina Avatar answered Nov 07 '22 09:11

Kenji Kina