AuthorizeAttribute has a separate responsibility: determine if the user is allowed. This can be used in several places of the application for various reasons.
Any actions taken as a result of non-authorization (for example, returning an HTTP 401 response) are delegated to a handler of type ActionResult , which is set to the AuthorizationContext.Result property. For example, the default implementation of AuthorizeAttribute.HandleUnauthorizedRequest is used here:
protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
If you are trying to perform an audit when the user is not logged in, you should put the audit in the ActionResult handler, and not in the user AuthorizeAttribute . This ensures that an audit will only be performed if an ActionResult is ActionResult (that is, when the current page is not authorized), but authorization is not checked in all cases.
public class AuthorizeWithLoggingAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new LoggingActionResult(new HttpUnauthorizedResult(), filterContext); } } public class LoggingActionResult : ActionResult { private readonly ActionResult innerActionResult; private readonly AuthorizationContext filterContext; public LoggingActionResult(ActionResult innerActionResult, AuthorizationContext filterContext) { if (innerActionResult == null) throw new ArgumentNullException("innerActionResult"); if (filterContext == null) throw new ArgumentNullException("filterContext"); this.innerActionResult = innerActionResult; this.filterContext = filterContext; } public override void ExecuteResult(ControllerContext context) {
NOTE. I would call them AuthorizeWithAuditingAttribute and AuditingActionResult , since you explicitly need an audit, not registration in this case.
NightOwl888
source share