How do I add impersonation in MVC ASP.NET Identity

2020-07-30 03:49发布

问题:

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.

回答1:

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);


回答2:

Thanks for this question as it helped me find a number of solutions including yours and @trailmax. After some thought I went about this a different way, as I just needed to change some of the Claims to do the impersonation. I call this semi-impersonation, as it just changes a few things rather than totally change the user.

Like trailmax I have written a blog post on my approach with all the code. Below I have summarised how it works.

  1. I add a session cookie with the impersonation information I needed to change in the current user to allow them to access information belonging to another user. I my case I had a key to some data.

  2. I then use the new MVC's 5 AuthenticationFilter OnAuthentication method to a) look for the impersonation cookie. If it found it then it changed the Claims in the current ClaimsPrincipal, which the filter would then propagate through the application.

  3. Coming out of impersonation mode was achieved by deleting the cookie, which you do by setting its expire date to a date prior to now.

The benefits are much more control over the level of access, but it won't work in all cases. In my article I compare my approach with @trailmax's approach to bring out the benefits of each implementation.