Search code examples
c#asp.net-mvcsimplemembership

Override a controller's [Authorize(Roles="X")] filter in an action of that controller


In an MVC app certain controller has access restricted by a role (there is an Authorize filter with a role attached to controller). Now the client decided that one of the actions in this controller should be available to all authenticated users (so AllowAnonymous filter alone won't do the trick and adding Authorize filter after AllowAnonymous doesn't work). How do I go about doing that?

In my case I can't really move the action to another controller and dropping the filter on controller and then adding it to all actions, but one doesn't sound like a good idea.


Solution

  • AllowAnonymous filter will make the action ignore all Authorize filters, so a quick and dirty solution would be to include the condition directly in the action (in this case checking if the user is authenticated). Finally, if the condition is not met return HttpUnauthorizedResult, to retain the default "redirect to login page" behavior.

    [AllowAnonymous]
    public ActionResult ActionAvailableToEveryone()
    {
        if (!User.Identity.IsAuthenticated)
        {
            return new HttpUnauthorizedResult();
        }
        return View();
    }
    

    There might be better\more elegant solutions to the problem, but changing membership provider or writing a custom filter just for a single action sounds like overkill.