ASP.NET Core 1.1用户身份模拟

时间:2017-05-29 21:19:49

标签: c# asp.net-identity impersonation asp.net-core-1.1 asp.net-core-identity

在尝试使用.Net Core的身份实现用户模拟功能时,缺乏信息。我试图让this ASP.NET MVC 4.6 code在ASP.NET Core中工作,但面对.NET Core不再支持的一些代码行。

以下是传入userName并以用户身份登录的原始4.6代码。

public async Task ImpersonateUserAsync(string userName)
{
    var context = HttpContext.Current;

    var originalUsername = context.User.Identity.Name;

    var impersonatedUser = await userManager.FindByNameAsync(userName);

    var impersonatedIdentity = await userManager.CreateIdentityAsync(impersonatedUser, DefaultAuthenticationTypes.ApplicationCookie);
    impersonatedIdentity.AddClaim(new Claim("UserImpersonation", "true"));
    impersonatedIdentity.AddClaim(new Claim("OriginalUsername", originalUsername));

    var authenticationManager = context.GetOwinContext().Authentication; 

    authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, impersonatedIdentity);
}

我已经完成了这项工作,但仍然遇到context.GetOwinContext().Authentication部分需要使用当前Cookie注销,并使用此新用户登录。

public async Task<IActionResult> ImpersonateUserAsync(string userName)
{
    var originalUsername = _httpContextAccessor.HttpContext.User.Identity.Name;

    var impersonatedUser = await _userManager.FindByNameAsync(userName);

    var impersonatedIdentity = await _userManager.CreateAsync(impersonatedUser);
    await _userManager.AddClaimAsync(impersonatedUser, new Claim("UserImpersonation", "true"));
    await _userManager.AddClaimAsync(impersonatedUser, new Claim("OriginalUsername", originalUsername));

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

有没有人采用这种方法?

1 个答案:

答案 0 :(得分:1)

使用HttpContext.Authentication

public async Task<IActionResult> ImpersonateUserAsync(string userName) {
    var context = HttpContext; //Property already exists in Controller

    var originalUsername = context.User.Identity.Name;

    var impersonatedUser = await _userManager.FindByNameAsync(userName);

    var impersonatedIdentity = await _userManager.CreateAsync(impersonatedUser);
    await _userManager.AddClaimAsync(impersonatedUser, new Claim("UserImpersonation", "true"));
    await _userManager.AddClaimAsync(impersonatedUser, new Claim("OriginalUsername", originalUsername));

    var authenticationManager = context.Authentication; 
    var cookie = DefaultAuthenticationTypes.ApplicationCookie;
    await authenticationManager.SignOutAsync(cookie);
    await authenticationManager.SignInAsync(cookie, impersonatedIdentity, 
        new AuthenticationProperties() { IsPersistent = false });

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

参考文档Using Cookie Middleware without ASP.NET Core Identity