Impersonate the user in ASP.net core

1 minute

Impersonate the user in ASP.net core

A recent project had a requirement to impersonate the current user when connecting to a SQL server instance - not sure why they wanted to do it this way, I've never worked on a project where this was done - it's always been the case that the app pool user is given access to the database so there is only one account to manage. To be fair the users accessing this app were all in a single group that was given access to the database - so still only a single thing to maintain but it still give me a bit of extra work to do.

Here's the middleware implementation that I wrote to impersonate the current user for all requests.

public class ImpersonationMiddleWare
{
	private readonly RequestDelegate _next;

	public ImpersonationMiddleWare(RequestDelegate next)
	{
		_next = next;
	}

	public async Task Invoke(HttpContext context)
	{
		var user = (WindowsIdentity)context.User.Identity;

        await WindowsIdentity.RunImpersonated(user.AccessToken, async () =>
        {
            await _next.Invoke(context);
        });
	}
}

and add the following in Startup.cs

app.UseMiddleware<ImpersonationMiddleWare>();

Now when the web app connects to the database it sends over the credentials of the current user.

comments powered by Disqus