bbu*_*ver 6 c# impersonation claims-based-identity asp.net-core-identity asp.net-core-1.1
假设我有以下角色:
行政
用户
我希望 Admin 角色模拟具有 User 角色的特定用户帐户,但不知道该特定用户帐户的密码。
管理员应该能够模拟应用程序中的任何用户,并能够以用户自己的身份浏览应用程序。 我找到了一个链接,其中实际上是在 ASP.NET MVC 4.6 中实现的,但是在将其转换为 Core 版本时有点头疼。
主要是因为链接中的最后一行代码
authenticationManager.SignIn(new AuthenticationProperties()
{ IsPersistent = false }, impersonatedIdentity);
Run Code Online (Sandbox Code Playgroud)
SignIn.NET Core 中的where参数不允许IdentityResult再传递类 (impersonatedIdentity)。它现在只能采取ClaimsPrincipal。
所以我最终做的是这个,
public async Task<IActionResult> ImpersonateUserAsync(string userName)
{
var impersonatedUser = await _userManager.FindByNameAsync(userName);
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, impersonatedUser.FirstName, ClaimValueTypes.String),
new Claim(ClaimTypes.Surname, impersonatedUser.LastName, ClaimValueTypes.String),
new Claim(ClaimTypes.Email, impersonatedUser.Email, ClaimValueTypes.String)
};
var user = new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme));
var authenticationManager = _httpContextAccessor.HttpContext.Authentication;
await authenticationManager.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await authenticationManager.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user, new AuthenticationProperties() { IsPersistent = false });
return RedirectToAction("Index", "Home");
}
Run Code Online (Sandbox Code Playgroud)
我填充了必要的声明并将其传递给了ClaimsPrincipal所以SignInAsync现在可以使用var user. 但是,这似乎我实际上并没有以AspNetUsers表中找到的用户身份登录,该用户具有以前由管理员角色分配的角色和权限。老实说,我希望上面的代码至少以我在var claims.
我需要采取哪些正确步骤才能以AspNetUsers表中定义的用户帐户身份登录,以便管理员能够以用户自己的身份浏览应用程序?