gpt4 book ai didi

c# - 在桌面应用程序中通过 VPN 模拟用户

转载 作者:太空狗 更新时间:2023-10-29 19:48:10 27 4
gpt4 key购买 nike

我在尝试在桌面应用程序中模拟事件目录用户时遇到问题。每次我使用 LogOn API 时,结果都是错误的。

用户和域确实存在,因为我还可以通过同一应用程序上的 DirectoryServices.AccountManagement 对用户进行身份验证。

已阅读 Microsoft 站点中有关模拟的文档,甚至还阅读了此处堆栈中的一些帖子。此外,使用 SimpleImpersonation 库得到了相同的结果。

public class Demo
{
private WindowsImpersonationContext impersonationContext = null;

[DllImport("advapi32.dll", SetLastError = true)]
private static extern int LogonUser(string lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);
private void Enter()
{
try
{
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
string userName = "myValidUser";
string domain = "my.domain.example";
string password = "myValidPassword";

if (LogonUser(userName, domain, password, (int)LogonType.LOGON32_LOGON_INTERACTIVE, (int)LogonProvider.LOGON32_PROVIDER_WINNT35, ref token) != 0)
{
WindowsIdentity WindowsIdentityPrincipal = new WindowsIdentity(token);
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
WindowsIdentity tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
}
else
{
throw new Win32Exception(new Win32Exception(Marshal.GetLastWin32Error()).Message);
}
}
else
{
//throws username or pass incorrect
throw new Win32Exception(new Win32Exception(Marshal.GetLastWin32Error()).Message);
}
}
catch (Exception exc)
{
throw exc;
}
}

public enum LogonProvider
{
LOGON32_PROVIDER_DEFAULT = 0,
LOGON32_PROVIDER_WINNT35 = 1,
LOGON32_PROVIDER_WINNT40 = 2,
LOGON32_PROVIDER_WINNT50 = 3
}

private enum LogonType
{
LOGON32_LOGON_INTERACTIVE = 2,
LOGON32_LOGON_NETWORK = 3,
LOGON32_LOGON_BATCH = 4,
LOGON32_LOGON_SERVICE = 5,
LOGON32_LOGON_UNLOCK = 7,
LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
LOGON32_LOGON_NEW_CREDENTIALS = 9,
}
}

我不知道它不工作的原因是否是我的计算机在外部网络上运行并通过 VPN 连接/验证到公司网络。

Edit 1. The resulting error code is 1326 (unknown user name or bad password)

Edit 2. The method is trying to obtain the identity token for later use on thread impersonation.

最佳答案

您可能需要查看 LogonUser function 的文档.

如果您的用户名格式为user@domain.example 那么您需要传入:

  • lpszUserName = "user@domain.example"
  • lpszDomain = null

如果您的用户名格式为domain\user 那么您需要传入:

  • lpszUserName = “用户”
  • lpszDomain = "域"

以错误的方式处理完全限定的用户名将导致您看到的错误代码。

关于c# - 在桌面应用程序中通过 VPN 模拟用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56448864/

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