Search code examples
c#.netasp.net-mvcantiforgerytoken

.NET MVC, Do something after ValidateAntiForgeryToken check fails


In my form I have

@Html.AntiForgeryToken()

and the receiving controller action has

    [HttpPost, ValidateAntiForgeryToken]  
    public ActionResult Login(LoginViewModel model)  
    {
      //if detects a post request missing token, 
      //I wish to log form info for later inspection
    }

When a post request missing token occurs, the framework does not proceed into the method. If I wish to log form info for later inspection, what can I do and where?


Solution

  • Another approach is to create a Custom Exception Filter to catch AntiForgery exceptions and log the form details from there, details below:

    public class AntiForgeryExceptionAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            // ANTIFORGERY TOKEN NOT PRESENT
            if (!filterContext.ExceptionHandled && filterContext.Exception is HttpAntiForgeryException)
            {
                var request = new HttpRequestWrapper(System.Web.HttpContext.Current.Request);
                // Use your own logging service to log the results
                var _logger = new LoggingService();
                foreach (var key in request.Form.AllKeys)
                {
                    var value = request.Form[key];
                    // "key" is the form input name and "value" is the form input value
                    _logger.Log("~~> " + key + " ==> " + value);
                }
    
                filterContext.ExceptionHandled = true;
            }
        }
    }
    

    and register the custom filter in global.asax:

    protected void Application_Start()
    {
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        GlobalFilters.Filters.Add(new AntiForgeryExceptionAttribute());
    }