我正在将ASP.NET MVC 5.1应用程序从MembershipProvider迁移到ASP.NET Identity v2.0。我在应用程序中拥有的功能之一是用户模拟:管理员可以像在该站点上注册的任何其他用户一样登录,而无需知道密码。
我使用此代码来实现MembershipProvider的用户模拟,并且它不适用于Identity库。
如何在ASP.NET Identity中实现用户模拟(不是IIS模拟)?
我已经找到了解决这个问题的方法。
基本上,我添加了具有管理员用户名的声明,如果该声明存在,我知道正在模拟。当管理员想要停止模拟时,系统会为声明检索原始用户名,删除旧的模拟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模拟用户。
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