I need to implement user impersonation through a HTTP header. For example, a user will send a request to /api/something
with the header impersonate=someUser
.
I tried to following process:
- User gets authenticated by one of multiple authentication schemes.
- The authenticated user gets replaced by the impersonated user, if it passes some security checks.
- The
/api/something
endpoint is called
I wrote some custom middleware for this, that runs just after the builtin authentication middelware:
if (!context.Request.Headers.TryGetValue("%Impersonation header%", out StringValues subject))
{
await _next(context);
return;
}
if (context.User?.Identity?.IsAuthenticated != true)
{
// return error
}
...
context.User = impersonatedUser
await _next(context);
However, when it finally reaches the controller, the initial user is still used because the ClaimsPrincipal
has been replaced by the default authorization into a new object with two identities. The first identity is the real user, the second identity is the impersonated user.
I could potentially resolve the user then using the second identity, but I'm not sure this process is following best practices?
Edit: this is for ASP.NET Core 2.2 / 3.1