我有来自常规 mvc 应用程序的以下代码,它通过模拟用户上传文件
public class PublicController : Controller
{
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
public SomeActionMethod(model containing file)
{
if (ImpersonateValidUser(userName: "someuserwithpowertoupload", domain: "", password: "somepassword"))
{
path = "Somepath";
file.SaveAs(path);
}
}
private bool ImpersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, impersonationLevel: 2, hNewToken: ref tokenDuplicate) != 0)
{
using (tempWindowsIdentity = new WindowsIdentity(tokenDuplicate))
{
this.impersonationContext = tempWindowsIdentity.Impersonate();
if (this.impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
}
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (tokenDuplicate != IntPtr.Zero)
{
CloseHandle(tokenDuplicate);
}
return false;
}
这里的问题是 WindowsImpersonationContext 在 .net core 中不存在。任何人都可以提供模拟用户的代码片段吗?微软文档在这里https://learn.microsoft.com/en-us/dotnet/standard/security/impersonating-and-reverting https://learn.microsoft.com/en-us/dotnet/standard/security/impersonating-and-reverting不是很有帮助。
谢谢。