Search code examples
asp.net-coreiis.net-8.0iis-10cookie-authentication

ASP.NET Core 8.0 MVC web app & IIS 10 - how to include the user name in the IIS log when the cookie authentication is used?


I have an ASP.NET Core 8.0 MVC app running on IIS 10 and which uses cookie authentication. I noticed that IIS doesn't include the user name in the log after the user is authenticated. Logging the user name in the IIS log is enabled.

This application has been converted from an ASP.NET MVC & webforms app. Previously, the users were authenticated via forms authentication, and IIS logged the user name in each request (after the user was authenticated).

Any idea on how to make IIS log the user name in the context of an ASP.NET Core app that uses cookie authentication?

TIA

Edit: Another way to do it would be to use:

but then some of the logging will be duplicated because the IIS logging is turned on (for policy reasons).

If I don't find an answer I will use the W3CLogger.


Solution

  • According to this issue, you could find it will not add the cs-username by default.

    So if you want to log the username, you should use custom field for the IIS logs.

    You could add below codes inside the program.cs:

    app.Use(async (context, next) =>
    {
        if (context.User.Identity.IsAuthenticated && context.Features.Get<IServerVariablesFeature>() is IServerVariablesFeature serverVariables)
        {
            serverVariables["AUTH_USER"] = context.User.Identity.Name ?? "?";
         }
        await next.Invoke();
    });
    

    Then you could modify the IIS w3wc to add custom field. like below:

    enter image description here

    Result:

    enter image description here