Impersonation not working in ASP.NET Core Web application

Viewed 291

I created a web application based on ASP.NET Core 6 with Angular for the frontend. In this web application, I am using Windows Authentication to authenticate the users of the application. This is how the authentication is defined in the IIS settings: Windows Authentication Configuration IIS

The authentication itself works fine, but in my application I also need to impersonate the authenticated user in order to perform requests against another REST API (PI Web API). This is how I am currently trying to do this:

[HttpGet]
public string GetSelfUserInfo()
{
    try
    {
        WindowsIdentity user = (WindowsIdentity)User.Identity;
        
        WindowsIdentity.RunImpersonated(user.AccessToken, () =>
        {
            // Create HTTP client instance and perform the request
            PIWebApiClient client = new PIWebApiClient("https://<url>/piwebapi", true);
            PIUserInfo userInfo = client.System.UserInfo();

            return $"IdentityType: {userInfo.IdentityType}\nName: {userInfo.Name}\nIsAuthenticated: {userInfo.IsAuthenticated}\nImpersonationLevel: {userInfo.ImpersonationLevel}";
        });
    }
    catch (Exception ex)
    {
        return $"Exception during HTTP request: {ex}";
    }
}

For some reason, this code does not work as expected. The HTTP request seems to reach the REST API just fine, but the identity of the user does not arrive at the REST API. When I check the Security Eventlogs on the server hosting the REST API, I can see a successful logon (Event ID 4624) but the account name for this logon is ANONYMOUS LOGON: Anonymous login problem

I already checked via additional debug logging that the current user identity inside the WindowsIdentity.RunImpersonated block is indeed the user which I want to use for performing the request against the REST API.

Why is the user identity getting lost somewhere in this request and what can I do to fix this problem?

0 Answers
Related