ASP .NET Core - 以其他用户身份登录/模拟用户并返回

Jet*_*223 3 c# asp.net asp.net-identity asp.net-core

作为管理角色的成员,想要在我的 ASP .NET Core Web 应用程序中模拟另一个用户。

基本上我想这样做:

以其他用户身份登录

我知道我可以使用其他用户身份登录:

await _signInManager.SignInAsync(appuser, false);
Run Code Online (Sandbox Code Playgroud)

对于“返回我自己的帐户”按钮- 我如何知道我当前正在冒充另一个用户并提供返回我自己帐户的“路径”。

是否有针对这种情况的内置方法?

返回我的帐户

屏幕截图取自ASP.NET Zero

Jet*_*223 5

我用下面的代码解决了它。

在帐户控制器中:

    [Authorize(Roles="Administrators")]
    public async Task<IActionResult> ImpersonateUser(string id)
    {
        var appUser = await _userManager.FindByIdAsync(id);
        var userPrincipal = await _signInManager.CreateUserPrincipalAsync(appUser);
        userPrincipal.Identities.First().AddClaim(new Claim("OriginalUserId", User.FindFirst(x=>x.Type == ClaimTypes.NameIdentifier).Value));

        await _signInManager.SignOutAsync(); //sign out the current user

        //https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNetCore.Identity/IdentityCookieOptions.cs
        await HttpContext.Authentication.SignInAsync("Identity.Application", userPrincipal); //impersonate the new user

        return RedirectToAction("Index", "Home");
    }

    public async Task<IActionResult> StopImpersonation()
    {
        var originalUserId = User.Claims.First(x => x.Type == "OriginalUserId").Value;
        var appUser = await _userManager.FindByIdAsync(originalUserId);
        await _signInManager.SignInAsync(appUser, false);

        return RedirectToAction("Index", "Home");
    }
Run Code Online (Sandbox Code Playgroud)

OriginalUserId基本上,这会向模拟用户添加声明。通过检查此声明是否存在,我知道我当前正在冒充,并且可以使用 中的代码提供返回原始帐户的方法StopImpersonation

身份验证方案Identity.Application是默认的。