0

I created a custom Authorize attribute that inherits from AuthorizeAttribute. Part of the the customization is logging the user's access into a database.

public class Authorization : AuthorizeAttribute
{ 
  ...
  dbRepo.LogAccessEntry(parameters);
  ...
}

I want to be able to use this on the controller level as well as more granular control for certain actions such as in the following example:

[Authorization]
public class TestController : Controller
{
  public ActionResult Index()
  {
    ...
  }

  [Authorization (Roles="admin")
  public ActionResult SecureArea()
  {
    ...
  }

}

However, this will result in the custom Authorize logging this twice. I was looking at the answer here https://stackoverflow.com/a/16713334/5473973 which would lead me to using an override attribute but would prefer not to have to create another attribute to keep track of. Is there a way to differentiate at what level it is being called or distinguish whether or not there are additional attributes to check? Only when it is finished with the authorization chain, should the access be logged. Or is there a better solution to this?

Leonardo Henriques
  • 784
  • 1
  • 7
  • 22
Kevin H
  • 25
  • 7

1 Answers1

0

Based off of NightOwl888's response (https://stackoverflow.com/a/49175535/5473973), I ended up using the "AllowMultiple = false" attribute on my custom attribute. This allows the action Attribute to override the controller Attribute.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class Authorization : AuthorizeAttribute
{ 
  ...
  dbRepo.LogAccessEntry(parameters);
  ...
}
Kevin H
  • 25
  • 7