Implementing Audit Trails Using ASP.NET MVC ActionFilters

Accountability is always important, especially when dealing with systems that contain sensitive data. It can often be helpful to have an audit trail that will allow you to go back and retrace the steps that a user took, what they saw, where they went and ultimately what they may have done wrong.

This post will cover how to implement a very basic Audit trail within your ASP.NET MVC Application using custom ActionFilters, which will allow you to decorate specific Controllers and Actions that will be designated to log details of a specific user interaction to later identify (or incriminate) them if necessary.

The Problem

A specific user within your system continues to submit incorrect, misspelled and erroneous data in one of the areas of your sensitive application, however you have no current means of figuring out exactly who they are.

The Solution

We can solve this through creating a custom ActionFilter that we can use to decorate specific Controllers and Actions to be flagged as Auditable and will insert an Audit record into our Auditing database or table. First, we will create a very basic framework for a custom ActionFilter.

  1. public class AuditAttribute: ActionFilterAttribute  
  2. {  
  3.     public override void OnActionExecuting(ActionExecutingContext filterContext)  
  4.     {  
  5.         // Additional Auditing-based Logic Here  
  6.         base.OnActionExecuting(filterContext);  
  7.     }  
  8. }  
Establishing A Basic Audit Record

Then we will need to determine what kinds of information that we will want to store within each of our Audit Records, so we will create an Audit class to store the values and a Context that can be used to access it. Our class will initially consist of the following fields that will constitute a single Audit record: 
  • AuditID - A unique identifier for this specific Audit instance.
  • UserName - The UserName of the user performing the Action (if available).
  • IPAddress - The IP Address of the user performing the Action.
  • AreaAccessed - This will store the URL of the area that was accessed.
  • Timestamp - A Timestamp of when the User accessed the area.

Which might look like:

  1. // Example Audit Class  
  2. public class Audit  
  3. {  
  4.     // Audit Properties  
  5.     public Guid AuditID  
  6.     {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public string UserName  
  11.     {  
  12.         get;  
  13.         set;  
  14.     }  
  15.     public string IPAddress  
  16.     {  
  17.         get;  
  18.         set;  
  19.     }  
  20.     public string AreaAccessed  
  21.     {  
  22.         get;  
  23.         set;  
  24.     }  
  25.     public DateTime Timestamp  
  26.     {  
  27.         get;  
  28.         set;  
  29.     }  
  30.     // Default Constructor  
  31.     public Audit()  
  32.     {}  
  33. }  
  34. // Example AuditingContext   
  35. public class AuditingContext: DbContext  
  36. {  
  37.     public DbSet < Audit > AuditRecords  
  38.     {  
  39.         get;  
  40.         set;  
  41.     }  
  42. }  
Now we will need to implement a simple local database that will be used to store our Audit records and allow us to access them as well. This can be accomplished by adding the following area within the web.config of our project:
  1. <connectionStrings>   
  2.    <!-- Default Connection goes here -->  
  3.    <!-- Our Auditing Context -->  
  4.    <add name="AuditContext"  
  5. connectionString="Data Source=(LocalDB)v11.0;AttachDbFilename=|DataDirectory|Auditing.mdf;Integrated Security=True"  
  6.       providerName="System.Data.SqlClient"  
  7.    />  
  8. </connectionStrings>   
Decorating for Audit Season

Now that we have a very basic method of saving and retrieving Audit records, we can start fleshing out our custom ActionFilter to populate an Audit whenever a decorated action is performed. 
  1. public class AuditAttribute: ActionFilterAttribute  
  2. {  
  3.     public override void OnActionExecuting(ActionExecutingContext filterContext)  
  4.     {  
  5.         // Stores the Request in an Accessible object  
  6.         var request = filterContext.HttpContext.Request;  
  7.         // Generate an audit  
  8.         Audit audit = new Audit()  
  9.         {  
  10.             // Your Audit Identifier   
  11.             AuditID = Guid.NewGuid(),  
  12.                 // Our Username (if available)  
  13.                 UserName = (request.IsAuthenticated) ? filterContext.HttpContext.User.Identity.Name : "Anonymous",  
  14.                 // The IP Address of the Request  
  15.                 IPAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"] ? ? request.UserHostAddress,  
  16.                 // The URL that was accessed  
  17.                 AreaAccessed = request.RawUrl,  
  18.                 // Creates our Timestamp  
  19.                 TimeAccessed = DateTime.UtcNow  
  20.         };  
  21.         // Stores the Audit in the Database  
  22.         AuditingContext context = new AuditingContext();  
  23.         context.AuditRecords.Add(audit);  
  24.         context.SaveChanges();  
  25.         // Finishes executing the Action as normal   
  26.         base.OnActionExecuting(filterContext);  
  27.     }  
  28. }  
And we can now add our new [Audit] attribute to any available controllers or actions that we want this to be performed in.
  1. [Authorize]  
  2. public class HomeController: Controller  
  3. {  
  4.     public ActionResult NormalAction()  
  5.         {  
  6.             return View();  
  7.         }  
  8.         [Audit]  
  9.     public ActionResult AuditedAction()  
  10.         {  
  11.             return Content("Audit Fired!");  
  12.         }  
  13.         // Other Actions omitted for brevity  
  14. }  
Testing, Testing, One, Two Three

So after creating as many auditable actions as you desire, you can log in to your application and begin hitting as many of the [Audit] actions as you can to build a decent set of them within your Audit database. When you are all finished with this, we will create a very basic action to display our audit trail:
  1. public ActionResult ViewAuditRecords()   
  2. {  
  3.    var audits = new AuditingContext().AuditRecords;  
  4.    return View(audits);  
  5. }  
And after building it and accessing it, you will be presented with a very basic audit trail :

Audit Logging Message

Additional Functionality Coming Soon

This blog post covered establishing a very basic system for setting up auditing that could easily be expanded upon. A follow-up will be posted in the future and will discuss methods of adding additional functionality to the Auditing ActionFilter such as serializing Request Data using JSON (to see exactly what our users were posting into fields), creating relationships within Audit objects (to monitor User Sessions) and more!

You can download this current example to update, modify and change to suit your needs as well from the following link: 
  • Download this Basic Auditing Example from Github


Similar Articles