I was able to get an authenticated Active Directory user with just a few lines of code. I am not very experienced with Core authentication, in particular with statements, but maybe this will lead you to you, or at least help others who come along with a similar problem, but with AD.
The key lines are Enrich.FromLogContext() and app.Use(async...
public class Startup { public IConfigurationRoot Configuration { get; } public Startup(IHostingEnvironment env) { Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() // Populates a 'User' property on every log entry .WriteTo.MSSqlServer(Configuration.GetConnectionString("MyDatabase"), "Logs") .CreateLogger(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.WithFilter(new FilterLoggerSettings { { "Default", LogLevel.Information }, { "Microsoft", LogLevel.Warning }, { "System", LogLevel.Warning } }) .AddSerilog(); app.Use(async (httpContext, next) => { var userName = httpContext.User.Identity.IsAuthenticated ? httpContext.User.Identity.Name : "unknown"; LogContext.PushProperty("User", !String.IsNullOrWhiteSpace(userName) ? userName : "unknown"); await next.Invoke(); }); } }
For AD authentication through IIS / Kestrel for web.config, you need to set forwardWindowsAuthToken as follows:
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <aspNetCore ... forwardWindowsAuthToken="true" /> </system.webServer> </configuration>
source share