Skip to main content
A newer version of this page is available. .
All docs
V21.1

Audit the Current User or Host Identity (EF Core)

  • 2 minutes to read

The Audit Trail Module gets information on the user who changed an object from the Security System. If your application uses custom authentication instead of the Security System, you can use the IPrincipalProvider.User.Identity.Name property to determine the user as demonstrated below:

  1. In the ASP.NET Core Blazor application project (MySolution.Blazor.Server), create the following new classes:

    • MyUserProvider, which implements the IAuditUserProvider interface
    • MyAuditDefaultStringProvider, which is an AuditDefaultStringProvider descendant
    using System;
    using DevExpress.ExpressApp.Security;
    using DevExpress.Persistent.BaseImpl.EFCore.AuditTrail;
    // ...
    public class MyUserProvider : IAuditUserProvider {
        private readonly IPrincipalProvider principalProvider;
        public MyUserProvider(IPrincipalProvider principalProvider) {
            this.principalProvider = principalProvider;
        }
        public object GetUser() {
            return principalProvider.User.Identity.Name;
        }
        public object GetUserId() {
            return principalProvider.User.Identity.Name;
        }
        public Type GetUserType() {
            return typeof(string);
        }
    }
    
    public class MyAuditDefaultStringProvider : AuditDefaultStringProvider {
        public override string GetDefaultString(object targetObject, Type objectType, object objectKey) {
            if(targetObject.GetType().Equals(typeof(string))) {
                return targetObject.ToString();
            }
            return base.GetDefaultString(targetObject, objectType, objectKey);
        }
    }
    
  2. In the Startup.ConfigureServices method (the MySolution.Blazor.Server\Startup.cs file), do the following:
    • add the custom implementation of the IPrincipalProvider service (HttpContextPrincipalProvider);
    • set the AuditUserProviderType and AuditDefaultStringProviderType properties to the custom MyUserProvider and MyAuditDefaultStringProvider types.
    using DevExpress.ExpressApp.Security;
    //...
    public class Startup{
        public void ConfigureServices(IServiceCollection services){
            //...
            services.AddScoped(typeof(IPrincipalProvider), typeof(HttpContextPrincipalProvider));
            services.AddAuditTrail(options => {
                options.AuditUserProviderType = typeof(MyUserProvider);
                options.AuditDefaultStringProviderType = typeof(MyAuditDefaultStringProvider);
            }).AddAuditedDbContextFactory<MySolutionEFCoreDbContext>();
        }
    }
    

Note

The MyUserProvider and MyAuditDefaultStringProvider types are registered as scoped services. You can use the IAuditUserProvider and IAuditDefaultStringProvider interfaces to access them.