Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you enable [Authorize] for controller but disable it for a single action?

I would like to use [Authorize] for every action in my admin controller except the Login action.

[Authorize (Roles = "Administrator")]
public class AdminController : Controller
{
    // what can I place here to disable authorize?
    public ActionResult Login()
    {
        return View();
    }
}
like image 734
Todd Smith Avatar asked Nov 30 '08 22:11

Todd Smith


2 Answers

You can decorate your controller with [Authorize] and then you can just decorate the method that you want to exempt with [AllowAnonymous]

like image 91
Ben Pretorius Avatar answered Sep 27 '22 21:09

Ben Pretorius


I don't think you can do this with the standard Authorize attribute, but you could derive your own attribute from AuthorizeAttribute that takes a list of actions to allow and allows access to just those actions. You can look at the source for the AuthorizeAttribute at www.codeplex.com for ideas on how to do this. If you did, it might look like:

[AdminAuthorize (Roles = "Administrator", Exempt = "Login, Logout") ]
public class AdminController : Controller
{
    public ActionResult Login()
    {
        return View();
    }

    public ActionResult Login()
    {
        return View();
    }

    ... other, restricted actions ...
}

EDIT: FYI, I eventually ran across a need to do something similar on my own and I went a different direction. I created a default authorization filter provider and apply a global authorize filter. The authorization filter provider uses reflection to check if an action or controller has a specific authorize attribute applied and, if so, defers to it. Otherwise, it applies a default authorization filter. This is coupled with a PublicAttribute derived from AuthorizeAttribute that allows public access. Now, I get default secured access, but can grant public access via [Public] applied to an action or controller. More specific authorization can also be applied as necessary. See my blog at http://farm-fresh-code.blogspot.com/2011/04/default-authorization-filter-provider.html

like image 31
tvanfosson Avatar answered Sep 27 '22 22:09

tvanfosson