1

Using Asp.Net MVC 5 and Identity v2, I have a controller action like:

[Authorize]
public ActionResult SemiSecureAction(string parameter)
{
   var model = SomeService.InitModel(parameter);
   // some controller logic
   return View(model);
}

I need to have that [Authorize]attribute on this action only if the parameter meets a condition. (e.g. !String.IsNullOrEmpty(parameter))

That is, I need to authorize a user only if the action's parameter meets a condition, and I need to have the same behavior in that case as the [Authorize] attribute does (e.g. redirect to login page with a returnUrl, etc.).

How can I do this? How can I use MVC controller annotations conditionally?

A. Burak Erbora
  • 1,054
  • 2
  • 12
  • 26

1 Answers1

5

You're better off writing your own custom attribute that implements AuthorizeAttribute. Here is a SO example of how to do that

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles).

What you describe in your question is impossible to achieve. By the time the parameter parameter has been passed into the action method, [Authorize] has already executed.

By creating a custom attribute, you would have access to the route values passed to the action method (which you could pick up from the passed HttpContextBase given to AuthorizeCore()). You can then perform any logic you like, based on the value of parameter.

Community
  • 1
  • 1
Jason Evans
  • 28,906
  • 14
  • 90
  • 154