4

I want to make a custom AuthorizeAttribute class as described here: Override Authorize Attribute in ASP.NET MVC.

The trick is, whether or not the user is authorized depends not just on what method he is executing, but the parameter as well:

[MyCustomAuthorize(id)]
[HttpGet]
public ActionResult File(Guid id)
{

}

Basically, the user will be authorized to see some Files, but not others, so I want to pass the id to my custom authorize attribute. But I can't seem to do this because the name 'id' isn't in scope.

I know I could do the logic to make sure the user has access to that File at the beginning of the method, but I have several methods that would all need this done, and it would be much cleaner if I could do it as part of the [Authorize] attribute.

Community
  • 1
  • 1
GendoIkari
  • 11,734
  • 6
  • 62
  • 104

2 Answers2

1

No, that's not legal C#.

You can access the RouteValues inside the AuthorizeAttribute subtype, however.

Inside, e.g., OnAuthorization, you can do:

object id = filterContext.RouteData.Values["id"];

Be careful, though. You really need to know what you're doing here. The interaction between authentication, authorization, and caching is complex.

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • Hmm, I probably don't qualify in the "really know what I'm doing" category. Would you recommend that I just check if they have permissions inside each method instead? – GendoIkari Oct 04 '11 at 19:00
  • Not necessarily. If an action result is cached, it won't execute *at all* when the user does a `GET`. Hence permission checks in the action won't run. Usually, an off the shelf solution like the role provider or AzMan is best for those who don't want to re-invent the wheel. – Craig Stuntz Oct 04 '11 at 19:36
-4

Maybe the last answer in 2011 was correct for that version HOWEVER it is possible. Create a public int (or whatever it is you need) and use that. Example:

public class RestrictToTemplateManagers : AuthorizeAttribute
{
    public string GUID { get; set; }
}

[RestrictToTemplateManagers(GUID="ABC")]
public class ImportTemplatesController : Controller
{

}
Bryce
  • 664
  • 6
  • 17
  • 1
    Except that your answer still restricts it based on a static value, not what was passed into the method. – Kyle W Mar 13 '17 at 18:38