ASP .NET核心 - 以其他用户身份登录/模仿用户和返回
问题描述:
作为管理角色的成员想在我的ASP .NET Core Web应用程序中模拟另一个用户。ASP .NET核心 - 以其他用户身份登录/模仿用户和返回
基本上我想这样做:
我知道我可以与其他用户登录:
await _signInManager.SignInAsync(appuser, false);
一个按钮“回到我自己的帐户” - 我如何知道我目前正在冒充另一个用户并为我自己的帐户提供“退款”。
这种情况下是否有内置方法?从ASP.NET Zero
答
采取
截图我用下面的代码解决了这个问题。
在的AccountController:
[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");
}
基本上,这增加了如权利要求OriginalUserId
到模拟的用户。通过检查此声明是否存在,我知道我目前正在冒充,并可以使用StopImpersonation
中的代码提供回原始帐户的方式。
验证方案Identity.Application
是默认设置。
+0
好的解决方案!很高兴我的博客帮助 – trailmax
不知道这是否会在Core中工作,但这就是我在Identity v2中所做的工作:http://tech.trailmax.info/2014/06/user-impersonation-with-asp-net-identity- 2 /我相信核心原则没有大规模改变 – trailmax
@trailmax谢谢。这是正确的方向(请参阅我的回答) – Jetro223