试图用.net core的身份实现用户模仿功能时缺乏信息。我正在尝试使此ASP.NET MVC 4.6代码在ASP.NET Core中起作用,但面对一些代码,这些代码不再支持。
因此,以下是要通过userName
并登录用户的原始4.6代码。
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);
}
我已经到了这里,但是粘贴在context.GetOwinContext().Authentication
部分,我需要与当前的cookie登录,并与此新用户登录。
public async Task<IActionResult> ImpersonateUserAsync(string userName)
{
var originalUsername = _httpContextAccessor.HttpContext.User.Identity.Name;
var impersonatedUser = await _userManager.FindByNameAsync(userName);
var impersonatedIdentity = await _userManager.CreateAsync(impersonatedUser);
await _userManager.AddClaimAsync(impersonatedUser, new Claim("UserImpersonation", "true"));
await _userManager.AddClaimAsync(impersonatedUser, new Claim("OriginalUsername", originalUsername));
return RedirectToAction("Index", "Home");
}
有人做过这种方法吗?
使用HttpContext.Authentication
。
public async Task<IActionResult> ImpersonateUserAsync(string userName) {
var context = HttpContext; //Property already exists in Controller
var originalUsername = context.User.Identity.Name;
var impersonatedUser = await _userManager.FindByNameAsync(userName);
var impersonatedIdentity = await _userManager.CreateAsync(impersonatedUser);
await _userManager.AddClaimAsync(impersonatedUser, new Claim("UserImpersonation", "true"));
await _userManager.AddClaimAsync(impersonatedUser, new Claim("OriginalUsername", originalUsername));
var authenticationManager = context.Authentication;
var cookie = DefaultAuthenticationTypes.ApplicationCookie;
await authenticationManager.SignOutAsync(cookie);
await authenticationManager.SignInAsync(cookie, impersonatedIdentity,
new AuthenticationProperties() { IsPersistent = false });
return RedirectToAction("Index", "Home");
}
使用cookie中间件的参考文档,没有ASP.NET核心身份