How to do this
IdentityServer4 does not prescribe any authentication providers. It just acts as one itself for other OIDC clients. That's why you can use third-party login providers, local accounts and whatever else.
Create an ImpersonationController in your IdentityServer.
Make sure, that only your administrators can access this page.
[Authorize(Policy = "CanImpersonate")]
Build a page, in which you can input a User ID, that the admin wants to impersonate.
When posting that form with the intended User ID, use the SignInManager<>
class to Sign in the current user.
You can even build a dropdown, what external login provider you'd like to impersonate with, if that is importatant to you.
Use the ExternalLoginSignInAsync
method, otherwise the plain SignInAsync(user, false)
method.
You are then already signed in as that user on Identity Server. When your client applications request sign-in, IdentityServer will notice your "forged" session and will redirect back to the client immediately with your currently signed in account.
You are now impersonating that user in your client application and on IdentityServer.
If you SignOut on IdentityServer, you will be "promoted" again to your previously logged in account (if still signed in as different identity), or will need to sign in as your actual administrator account again.
What you need to be careful with
Side effects
This is obviously a topic for debate. I'm assuming you want to add this feature, so that you can reproduce user issues, or do some action as the user.
If you do this without users knowing, be very careful about side-effects of whatever actions are done during the impersonation. Are E-Mails sent, or similar notifications.
There is a lot of trust to be lost going this route.
Law
This is also a concern for privacy. Who is able to access the details. What details are revealed, when impersonating a user on your platform.
A recommendation
Don't impersonate users.
Implement a controlled way, in which your administrators can perform the required work. Then you have a consistant audit log, and whatever a signed in user does to your system, you can be sure that it was that user, and not your administrator impersonating that account.