我找到了解决这个问题的办法。
基本上,我使用管理员用户名添加声明,如果此声明存在,我就知道正在发生冒充行为。当管理员想要停止模拟时,系统会检索声明的原始用户名,删除旧的模拟 cookie 并为管理员创建一个新的 cookie:
[AuthenticateAdmin] // <- make sure this endpoint is only available to admins
public async Task ImpersonateUserAsync(string userName)
{
var context = HttpContext.Current;
var originalUsername = context.User.Identity.Name;
var impersonatedUser = await userManager.FindByNameAsync(userName);
var impersonatedIdentity = await userManager.CreateIdentityAsync(impersonatedUser, DefaultAuthenticationTypes.ApplicationCookie);
impersonatedIdentity.AddClaim(new Claim("UserImpersonation", "true"));
impersonatedIdentity.AddClaim(new Claim("OriginalUsername", originalUsername));
var authenticationManager = context.GetOwinContext().Authentication;
authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, impersonatedIdentity);
}
更多信息请参阅我的博文:使用 ASP.Net Identity 2 模拟用户.
Asp.Net Core 中的用户模拟
2017 年 7 月更新:这个主题非常流行,所以我研究了 Core 中的用户模拟,原理与更新的 API 非常相似。模仿方法如下:
[Authorize(Roles = "Admin")] // <-- Make sure only admins can access this
public async Task<IActionResult> ImpersonateUser(String userId)
{
var currentUserId = User.GetUserId();
var impersonatedUser = await _userManager.FindByIdAsync(userId);
var userPrincipal = await _signInManager.CreateUserPrincipalAsync(impersonatedUser);
userPrincipal.Identities.First().AddClaim(new Claim("OriginalUserId", currentUserId));
userPrincipal.Identities.First().AddClaim(new Claim("IsImpersonating", "true"));
// sign out the current user
await _signInManager.SignOutAsync();
// If you use asp.net core 1.0
await HttpContext.Authentication.SignInAsync(cookieOptions.ApplicationCookieAuthenticationScheme, userPrincipal);
// If you use asp.net core 2.0 (the line above is deprecated)
await HttpContext.SignInAsync(cookieOptions.ApplicationCookieAuthenticationScheme, userPrincipal);
return RedirectToAction("Index", "Home");
}
这是阻止冒充的方法:
[Authorize(Roles = "Admin")] // <-- Make sure only admins can access this
public async Task<IActionResult> StopImpersonation()
{
if (!User.IsImpersonating())
{
throw new Exception("You are not impersonating now. Can't stop impersonation");
}
var originalUserId = User.FindFirst("OriginalUserId").Value;
var originalUser = await _userManager.FindByIdAsync(originalUserId);
await _signInManager.SignOutAsync();
await _signInManager.SignInAsync(originalUser, isPersistent: true);
return RedirectToAction("Index", "Home");
}
完整解释在我的博客中:http://tech.trailmax.info/2017/07/user-impersonation-in-asp-net-core/GitHub 上的完整代码示例:https://github.com/trailmax/AspNetCoreImpersonation