Audit.NET icon indicating copy to clipboard operation
Audit.NET copied to clipboard

Question: Track Audit.WebApi and Audit.EntityFramework Related Records

Open gato-negro opened this issue 8 years ago • 7 comments

Hi, this is not a bug but a question.

I use both Audit.WebApi and Audit.EntityFramework together after your help from another ticket.

I store all activity in my EF DB using the Audit.EntityFramework storing each table's data in a corresponding table eg: Products-> ProductAudits, Categories -> CategoryAudits At the same time i store all WebApi calls to another table named eg WebApiAudits.

What i would like to do is connect table WebApiAudits with the EF DB logs created by that call.

For example i have a web api endpoint named FakeCall. A call to it creates a new record in WebApiAudits for FakeCall. This call also causes some CRUD in the database leading to new records in CategoryAudits and ProductAudits. I am wondering if i could add a custom column to WebApiAudits so that i will be able to store info that connects this WebApiAudit record to the records in the different tables logs (CategoryAudits, ProductAudits ) that were created because of that api call.

Any help would be very appreciated

gato-negro avatar Jul 04 '18 15:07 gato-negro

AspNet Core WebApi, right?

thepirat000 avatar Jul 04 '18 16:07 thepirat000

For Asp.NET Core Web Api you could proceed as follows:

Add middleware to generate an id per request

On your startup logic:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Add middleware
    app.Use(async (context, next) =>
    {
        context.Items["RequestId"] = Guid.NewGuid();
        await next.Invoke();
    });

    app.UseMvc();
}

Setup a Custom Action that sets the id to a Custom Field on the event

Also on your starup logic

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    var svcProvider = services.BuildServiceProvider();
    // Add custom action
    Audit.Core.Configuration.AddCustomAction(ActionType.OnScopeCreated, scope =>
    {
        var requestId = svcProvider
            .GetService<IHttpContextAccessor>()
            .HttpContext.Items["RequestId"];
        scope.Event.CustomFields["RequestId"] = requestId;
    }
}

And then it really depends on your data provider, but you should be able to get the id from the event Custom Field with auditEvent.CustomFields["RequestId"] on any of the Audit Events within a request and they will have all the same id.

thepirat000 avatar Jul 04 '18 17:07 thepirat000

Also check the latest posts on the gitter chat https://gitter.im/Audit-NET/Lobby there is a similar question answered for both AspNet and AspNet Core.

Here is the AspNet version using a delegating handler:

public class CorrelationIdHandler : DelegatingHandler
{
    public const string HandlerKey = "Correlation-ID";
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpContext.Current.Items[HandlerKey] = request.GetCorrelationId().ToString();
        var response = await base.SendAsync(request, cancellationToken);
        return response;
    }
}

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MessageHandlers.Add(new CorrelationIdHandler());

        Audit.Core.Configuration.Setup()            
            .UseFileLogProvider(...);

        Audit.Core.Configuration.AddCustomAction(ActionType.OnScopeCreated, scope =>
        {
            var correlationId = HttpContext.Current.Items[CorrelationIdHandler.HandlerKey];
            scope.Event.CustomFields["RequestId"] = correlationId;
        });

        // Web API routes
        ...
    }
}

thepirat000 avatar Jul 04 '18 17:07 thepirat000

Hi, thanks for the fast and usefull replies. Yes, AspNet Core WebApi,

I already do something very similar. So, i have a guid column named EventId generated per api request. I save this both in webapiaudit table and in each table that stores data changes. So i have for example a record in webapiaudit with EventId: xxxxxx and 2 records in CategoryAudits with EventId: xxxxxx and 5 records in ProductAudits with EventId: xxxxxx.

In other words i know that the api call with eventId: xxxxxx caused the creation of 2 records in CategoryAudits and 5 records in ProductAudits. The problem is that i need to know somehow that the api call created records to CategoryAudits and ProductAudits and not in CustomerAudits, ItemsAudits, ... So, i when i need to search for eventId: xxxxxx i need a way to know in which tables to look because i have 200 tables but i only made new records in 2 of them. So to query just CategoryAudits and ProductAudits for records with that eventId, webapiaudit table needs to store info about which tables where affected.

Just wondering if you have done this before in case there is a more "prototyped" way of implementing such a scenario. If not no worries. I will keep track of the tables changing in a request context scoped parameter and eventually put that also in a field inside webapiaudits.

By the way, is it possible to store custom fields as columns instead of storing them as json inside EventData column?

Thank you again!

gato-negro avatar Jul 05 '18 09:07 gato-negro

By the way, is it possible to store custom fields as columns instead of storing them as json inside EventData column?

I'm assuming that you use the EntityFrameworkDataProvider to save the EF events and a SqlServerDataProvider to save the webapi events. Is that correct?

thepirat000 avatar Jul 05 '18 15:07 thepirat000

Anyway there is no default way to accomplish what you want. I can see different possible solutions:

  1. Store the all the audit events (EF and webapi) in the same place (i.e. just one big audit table)
  2. Maintain a list of affected entities on the httpcontext per request, and save it on the web api event.

For the latter, you can do like:

using Audit.Core;
using Audit.WebApi;
using Audit.EntityFramework;
//...
Audit.Core.Configuration.AddCustomAction(ActionType.OnScopeCreated, scope =>
{
    var httpContext = svcProvider.GetService<IHttpContextAccessor>().HttpContext;
    if (scope.Event.GetWebApiAuditAction() != null)
    {
        // WebApi event created, create the empty list of entities
        httpContext.Items["AffectedEntities"] = new List<string>();
    }
    else
    {
        var efEvent = scope.Event.GetEntityFrameworkEvent();
        if (efEvent != null)
        {
            // EF event created, add the affected entity names to the list
            var list = httpContext.Items["AffectedEntities"] as List<string>;
            list.AddRange(efEvent.Entries.Select(e => e.Table));
        }
    }
});

Audit.Core.Configuration.AddCustomAction(ActionType.OnEventSaving, scope =>
{
    var webApiEvent = scope.Event.GetWebApiAuditAction();
    if (webApiEvent != null)
    {
        // WebApi event about to be saved, set the affected entities as a custom field
        var httpContext = svcProvider.GetService<IHttpContextAccessor>().HttpContext;
        var list = httpContext.Items["AffectedEntities"] as List<string>;
        scope.SetCustomField("AffectedEntities", list);
    }
});

thepirat000 avatar Jul 05 '18 15:07 thepirat000

This is correct. Yes, i followed the 2nd way. thanks again for your time and all your help.

gato-negro avatar Jul 05 '18 20:07 gato-negro