public async Task <IActionResult> Impersonate(ImpersonationViewModel model) { var user = await _userManager.FindByIdAsync(model.UserId); var newPrincipal = await _claimsFactory.CreateAsync(user); if (model.UserId != User.FindFirstValue(TolkClaimTypes.ImpersonatingUserId)) { if (newPrincipal.IsInRole(Roles.SystemAdministrator)) { throw new InvalidOperationException("Cannot impersonate a system administrator user"); } var newIdentity = newPrincipal.Identities.Single(); ImpersonationHelper.SetupImpersonationClaims(User, newIdentity); } await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, newPrincipal); return(RedirectToAction("Index", "Home")); }
public override async Task ValidateAsync(CookieValidatePrincipalContext context) { var oldPrincipal = context?.Principal; await base.ValidateAsync(context); if (context.Principal == null || // Session rejected by base class, everyting is handled. ReferenceEquals(oldPrincipal, context.Principal)) // Same principal => not time for refresh yet. { return; } var impersonatingUserId = oldPrincipal.FindFirstValue(TolkClaimTypes.ImpersonatingUserId); if (impersonatingUserId != null) { var impersonatingIdentity = new ClaimsIdentity(); var impersonatingSecurityStamp = oldPrincipal.FindFirstValue(TolkClaimTypes.ImpersonatingUserSecurityStamp); impersonatingIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, impersonatingUserId)); impersonatingIdentity.AddClaim(new Claim(TolkClaimTypes.AspNetSecurityStamp, impersonatingSecurityStamp)); var impersonatingPrincipal = new ClaimsPrincipal(impersonatingIdentity); var impersonatingUser = await _signInManager.ValidateSecurityStampAsync(impersonatingPrincipal); if (impersonatingUser != null && await _userManager.IsInRoleAsync(impersonatingUser, Roles.Impersonator)) { var newIdentity = context.Principal.Identities.Single(); ImpersonationHelper.SetupImpersonationClaims(oldPrincipal, newIdentity); } else { context.RejectPrincipal(); await _signInManager.SignOutAsync(); } } }