ASP.NET 核心 1.1 用户身份模拟

ASP.NET Core 1.1 User Impersonation with Identity

在尝试使用 .Net Core 的身份实现用户模拟功能时,由于缺乏信息而陷入困境。我试图让 this ASP.NET MVC 4.6 code 在 ASP.NET Core 中工作,但遇到了一些 .NET Core 不再支持的代码行。

所以下面是原始的 4.6 代码,用于传入 userName 并以用户身份登录。

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

参考文档Using Cookie Middleware without ASP.NET Core Identity