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()
{
...
}
}
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.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With