Search code examples
c#asp.net-corehashicorp-vaultaudit.net

Audit.NET obtain database credentials dynamically


We are using Audit.NET library in our Asp.Net Core project to log user actions. Recently we have decided to use Hashicorp Vault to securely store and obtain secrets including database credentials. Vault engine automatically rotates database credentials on the configured period of time, so static credentials are not an option anymore.

Thus, we had to implement a service which will serve the current connection string (we are using PostgreSql) to the required services. In case of the DB context it is possible to get the connection string at runtime using the following code in Startup.cs:

 services.AddDbContext<AppDbContext>((serviceProvider, options) =>
        {
            var databaseCredentialsProvider = serviceProvider.GetRequiredService<IDbConnectionStringProvider>();
            var connectionString = databaseCredentialsProvider.GetConnectionString();
            options.UseNpgsql(connectionString);
        });

However, regarding the Audit.NET configuration, it seems that it can only set static credentials. We are using the following code in Startup.cs to configure the Audit.NET.

Audit.Core.Configuration.Setup()
            .UsePostgreSql(config => config
                    .ConnectionString(Configuration.GetConnectionString(""))
                    .Schema("")
                    .TableName("")
                    .IdColumnName("")
                    .DataColumn("", DataType.JSONB)
                    .LastUpdatedColumnName("");
            );

I've looked through the source code of UsePostgreSql - it sets the credentials once so it is not an option to use this extension method.

Is there any way to configure Audit.NET to obtain database credentials dynamically? Should I implement custom UsePostgreSql provider then?


Solution

  • With latest version you can now setup the configuration values as Functions, so the values will be retrieved when the audit events are created. For example:

    Audit.Core.Configuration.Setup()
        .UsePostgreSql(config => config
            .ConnectionString(_ => serviceProvider.GetRequiredService<IDbConnectionStringProvider>().GetConnectionString())
            .Schema("")
            .TableName("")
            .IdColumnName("")
            .DataColumn("", DataType.JSONB)
            .LastUpdatedColumnName("");
        );