Search code examples
asp.net-core.net-coreasp.net-core-mvcimpersonationasp.net-core-2.1

Is there a .net core 2.2 way of doing WindowsImpersonationContext?


This is not working private static WindowsImpersonationContext impersonationContext;

I am needing to be able to do this

tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);

impersonationContext = tempWindowsIdentity.Impersonate();

And then this

if (impersonationContext != null)
{
    impersonationContext.Undo();
    impersonationContext = null;
}

I was looking at this question/answer: WindowsImpersonationContext & Impersonate() not found in ASP.Core

However that doesn't seem to be a good match, does it?


Solution

  • ASP.NET Core doesn't implement impersonation. Apps run with the application identity for all requests, using app pool or process identity. If you need to explicitly perform an action on behalf of a user, use WindowsIdentity.RunImpersonated.

    WindowsIdentity.RunImpersonated(user.AccessToken, () =>
        {
            var impersonatedUser = WindowsIdentity.GetCurrent();
            var message =
                $"User: {impersonatedUser.Name}\tState: {impersonatedUser.ImpersonationLevel}";
    
            var bytes = Encoding.UTF8.GetBytes(message);
            context.Response.Body.Write(bytes, 0, bytes.Length);
        });
    

    You can read further @ Configure Windows Authentication in ASP.NET Core