0

I need help with logging in terms of MVC flow.

I have an securely authenticated Web API which people try to access. Because of restricted access to Web API methods, some people do not have access to it at all ([Authorize(roles=Admin)] and other role based attribute restrict access). But I want to log attempts by people to access it, even if they are not successful.

What would be the way to do it in an enterprise application? No vague answers please.

Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
Vivek Jaiswal
  • 97
  • 1
  • 1
  • 3
  • See [this answer](http://stackoverflow.com/a/32254851). You need to keep your authorization filter separate from your authorize attribute to add behavior to it. Attributes themselves have [no behavior](http://blog.ploeh.dk/2014/06/13/passive-attributes/), it is the filter that does the work. The place to hook in is the `HandleUnauthorizedRequest` method in a subclass of `AuthorizeAttribute`. You can use a decorator pattern to log the attempt before the original handler is executed (`filterContext.Result = new MyLogger(new HttpUnauthorizedResult(), filterContext);`). – NightOwl888 Apr 13 '17 at 12:46

1 Answers1

0

The most correct way would be to create a class that inherits ActionFilterAttribute (https://msdn.microsoft.com/en-us/library/system.web.mvc.actionfilterattribute.aspx) and override OnActionExecuting method. This can then be registered in the GlobalFilters in Global.asax.cs

This will only intercept requests that actually have a route.

Murad
  • 523
  • 4
  • 17