我想在我的ASP.NET Core App中"模仿"用户 - 作为支持人员的功能,以便可以有效地将其作为用户登录以解决问题。<<<<<<<<<。/p>
.net核心之前,在ASP.NET MVC5中,我们有这样的工作:
var impersonatedUser = await _userManager.FindByIdAsync(id);
var impersonatedIdentity = await _userManager.CreateIdentityAsync(impersonatedUser, DefaultAuthenticationTypes.ApplicationCookie);
//add the claims to allow us back to the current user and to flag that we're impersonating:
impersonatedIdentity.AddClaim(new Claim(ClaimTypes.UserImpersonationKey, bool.TrueString));
impersonatedIdentity.AddClaim(new Claim(ClaimTypes.OriginalUserIdKey, _currentUser.User.Id.ToString()));
//log in the impersonated user:
var authenticationManager = HttpContext.GetOwinContext().Authentication;
//log us out:
authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, impersonatedIdentity);
这将很好地为我们想模仿的用户创建一个身份,添加一些主张来告诉我们我们要模仿的应用,然后登录为该用户。索赔将被添加到cookie中,使其全部持续。
我现在试图在ASP.NET核心中进行此操作,但运气不多。如何获取用户,登录该用户,然后为该用户添加一些索赔。
我知道有多种方法可以在用户登录时向用户添加索赔,例如提供此处所述的自定义UserClaimsPrincipalFactory
- 但是,这向所有用户添加了索赔,我只想在我正在模仿。
到目前为止我的代码:
var user = await _userManager.FindByIdAsync(id.ToString());
await _signInManager.SignOutAsync();
await _signInManager.SignInAsync(user, true, "Cookies");
// Now if I could just add some claims to the user to flag we're in impersonation mode....
都在UserClaimsPrincipalFactory
中。
这是一些代码:
var principal = await _claimsPrincipalFactory.CreateAsync(user);
// Now add some claims to that
((ClaimsIdentity)principal.Identity).AddClaim(new Claim("Some Key", "Some value"));
// In my case, I want to sign out the current user and use this new principal with "extra" claims
await _signInManager.SignOutAsync();
await HttpContext.SignInAsync(Authentication.CookieScheme, principal, new Microsoft.AspNetCore.Authentication.AuthenticationProperties
{
IsPersistent = false
});
我的工厂被注入我的控制器:
IUserClaimsPrincipalFactory<User> claimsPrincipalFactory