临时向已签名的身份用户添加声明

时间:2017-06-27 20:09:07

标签: asp.net asp.net-mvc asp.net-core asp.net-identity asp.net-identity-2

我想"冒充"我的asp.net核心应用程序中的用户 - 作为支持人员的一项功能,以便他们可以有效地以用户身份登录以解决问题。

在.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 described here - 但是会向所有用户添加声明,而我我只想在我进行模拟时向用户添加声明。

到目前为止我的代码:

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....

1 个答案:

答案 0 :(得分:0)

全部都在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