Search code examples
c#azure-table-storage.net-8.0audit.net

How to connect AzureTableStorage using UserAssigned ManagedIdentity in the AuditTrail implementation using Audit.NET?


I have implemented Audit Trail in .NET 8 Web API application using great library which has a very good documentation also : https://github.com/thepirat000/Audit.NET/blob/master/src/Audit.WebApi/README.md

In this implementation I am using AzureStorageTableDataProvider (https://github.com/thepirat000/Audit.NET/tree/master/src/Audit.NET.AzureStorageTables) to store the audit events.

I am using the below code to connect to the AzureTableStorage here. Here I am using connectionstring.

public void AuditSetupOutput(IApplicationBuilder app)
{
    var options = new JsonSerializerOptions()
    {
        WriteIndented = true
    };

    Configuration.Setup()
    .JsonSystemAdapter(options)
    .UseAzureTableStorage(config => config
        .ConnectionString("ConnectionString")
        .TableName(evt => $"{_TargetTableName}{DateTime.UtcNow:MMMyyyy}")
        .ClientOptions(new TableClientOptions() { Retry = { MaxRetries = 3 } })
        .EntityBuilder(builder => builder
            .PartitionKey(auditEvent => auditEvent.EventType)
            .RowKey(auditEvent => Guid.NewGuid().ToString("N"))
            .Columns(col => col
                .FromDictionary(auditEvent => new Dictionary<string, object>()
                {
                    { "EventType", auditEvent.EventType },
                    { "UserName", auditEvent.Environment.UserName },
                    { "EventDuration", auditEvent.Duration },
                    { "DataSize", auditEvent.ToJson().Length },
                    { "Data", auditEvent.ToJson().Length >= 32000 ? CompressAuditEventData(auditEvent.ToJson()): auditEvent.ToJson()}
                }))));


    // Include the trace identifier in the audit events
    var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
    Configuration.AddCustomAction(ActionType.OnScopeCreated, scope =>
    {
        scope.SetCustomField("TraceId", httpContextAccessor.HttpContext?.TraceIdentifier);
    });

}

As most of Azure services are supporting Managed Identities. Is it possible to connect to the AzureTableStorage with UserAssigned ManagedIdentity in this case. If yes please help me to get some code samples as reference. Can anyone help me here with some code sample which will serve as a reference for my implementation


Solution

  • Looking at the source code here, it looks like you should be able to use managed identity.

    Can you please try something like:

    public void AuditSetupOutput(IApplicationBuilder app)
    {
        var options = new JsonSerializerOptions()
        {
            WriteIndented = true
        };
    
        Configuration.Setup()
        .JsonSystemAdapter(options)
        .UseAzureTableStorage(config => config
            .Endpoint(new Uri("https://account.table.core.windows.net", new DefaultAzureCredential())
            .TableName(evt => $"{_TargetTableName}{DateTime.UtcNow:MMMyyyy}")
            .ClientOptions(new TableClientOptions() { Retry = { MaxRetries = 3 } })
            .EntityBuilder(builder => builder
                .PartitionKey(auditEvent => auditEvent.EventType)
                .RowKey(auditEvent => Guid.NewGuid().ToString("N"))
                .Columns(col => col
                    .FromDictionary(auditEvent => new Dictionary<string, object>()
                    {
                        { "EventType", auditEvent.EventType },
                        { "UserName", auditEvent.Environment.UserName },
                        { "EventDuration", auditEvent.Duration },
                        { "DataSize", auditEvent.ToJson().Length },
                        { "Data", auditEvent.ToJson().Length >= 32000 ? CompressAuditEventData(auditEvent.ToJson()): auditEvent.ToJson()}
                    }))));
    
    
        // Include the trace identifier in the audit events
        var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
        Configuration.AddCustomAction(ActionType.OnScopeCreated, scope =>
        {
            scope.SetCustomField("TraceId", httpContextAccessor.HttpContext?.TraceIdentifier);
        });
    
    }
    

    Basically look at Endpoint(Uri endpoint, TokenCredential credential).