I am using ASP.net Core Identity, I have registered users in my application and I have assigned an Admin role to one of the users. Now I want that user to login to anyone else's account. As the Administrator of the site, that user should be able to sign in to any other user's account and can do any changes he wants.
Instead of creating a whole separate User management screen where admin will be able to update/delete users, I am thinking to let admin sign in to any of the existing user's account and change its information.
I am looking for a way in which my user which has an Admin role can sign in to any other user account in ASP.net Core Identity
You can use the .SignInAsync()
method from SignInManager
to log in as a specific user without knowing their passwords:
public class ImpersonateUserHandler : IRequestHandler<ImpersonateUser, CommandResult>
{
private readonly SignInManager<AppUser> _signInManager;
public ImpersonateUserHandler(SignInManager<AppUser> signInManager)
{
_signInManager = signInManager;
}
public async Task<CommandResult> Handle(ImpersonateUser command,
CancellationToken cancellationToken)
{
try
{
cancellationToken.ThrowIfCancellationRequested();
// Look up the user you're going to impersonate
var user = await _signInManager.UserManager.FindByIdAsync(command.UserId);
...
// Login
var signInResult = await _signInManager.SignInAsync(user, false);
...
}
catch(...)
{
...
}
...
}
}