gpt4 book ai didi

c# - ASP.NET Core 1.1 用户身份模拟

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:18 24 4
gpt4 key购买 nike

在尝试使用 .Net Core 的身份实现用户模拟功能时,由于缺乏信息而陷入困境。我正在尝试制作 this ASP.NET MVC 4.6 code在 ASP.NET Core 中工作,但面临一些 .NET Core 不再支持的代码行。

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

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");
}

有人用过这种方法吗?

最佳答案

使用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

关于c# - ASP.NET Core 1.1 用户身份模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44250420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com