Search code examples
asp.netasp.net-identity-2

How do I add impersonation in MVC ASP.NET Identity 2.0


I am wondering how I add user impersonation on mvc identity 2.0, I seen some people using this:

FormsAuthentication.SignOut();
FormsAuthentication.SetAuthCookie(user.UserName, false);

This wont work for me it wont even sign out I use :

AuthenticationManager.SignOut() 

So how do I go along doing this I have admin panel what lists users, I get the userId or userName, what exactly do I have to do? I have never used Claims so I dont understand it much I wont need to revert back to user they can just logout for now.


Solution

  • Here is the solution for anyone who else is having this issue - :

    var user = _db.AspNetUsers.Single(a => a.Id == id);
    
    var impersonatedUser = UserManager.FindByName(user.Email);
    
    var impersonatedIdentity = UserManager.CreateIdentity(impersonatedUser, DefaultAuthenticationTypes.ApplicationCookie);
    
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
    AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, impersonatedIdentity);