C# 使用用户名和密码模拟?
我在哪里声明Administrator用户名和密码 accessToken参数对我帮助不大C# 使用用户名和密码模拟?,c#,console-application,impersonation,C#,Console Application,Impersonation,我在哪里声明Administrator用户名和密码 accessToken参数对我帮助不大 我必须为它导入DLL吗 您需要p/调用API。它接受用户名、域和密码并返回令牌。这正是您必须使用的accesstoken。要获得它,您需要调用LogonUser方法: oops没有意识到我只是在这里有VB.net代码。想象一下C##) 在这里 外部方法声明: WindowsIdentity identity = new WindowsIdentity(accessToken); WindowsImpers
我必须为它导入DLL吗 您需要p/调用API。它接受用户名、域和密码并返回令牌。这正是您必须使用的accesstoken。要获得它,您需要调用LogonUser方法: oops没有意识到我只是在这里有VB.net代码。想象一下C##) 在这里 外部方法声明:
WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();
...
context.Undo();
以及执行:
Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
ByRef phToken As IntPtr) As Boolean
您需要获取用户的令牌。使用advapi32.dll中的p/invoke:
_Token = New IntPtr(0)
Const LOGON32_PROVIDER_DEFAULT As Integer = 0
'This parameter causes LogonUser to create a primary token.
Const LOGON32_LOGON_INTERACTIVE As Integer = 2
Const LOGON32_LOGON_NEWCREDENTIALS As Integer = 9
_Token = IntPtr.Zero
' Call LogonUser to obtain a handle to an access token.
Dim returnValue As Boolean = LogonUser(_User, _Domain, _Password, LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, _Token)
If False = returnValue Then
Dim ret As Integer = Marshal.GetLastWin32Error()
Console.WriteLine("LogonUser failed with error code : {0}", ret)
Throw New System.ComponentModel.Win32Exception(ret)
End If
_Identity = New WindowsIdentity(_Token)
_Context = _Identity.Impersonate()
示例:
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
out IntPtr phToken);
有没有一种不用密码的方法?我可以访问它,因为我正在模拟之前创建,我想我会问。我想应该在使用块之后调用
CloseHandle
(如中所述)以获取userToken
。或者这是由WindowsIdentity
以某种方式调用的?您好,如果这是ASP.NET应用程序,它的范围是什么?我应该在每个页面中调用此函数吗?您可能希望使用此代码而不是抛出SecurityException来很好地获取错误详细信息:抛出新的Win32Exception(Marshal.GetLastWin32Error())
IntPtr userToken = IntPtr.Zero;
bool success = External.LogonUser(
"john.doe",
"domain.com",
"MyPassword",
(int) AdvApi32Utility.LogonType.LOGON32_LOGON_INTERACTIVE, //2
(int) AdvApi32Utility.LogonProvider.LOGON32_PROVIDER_DEFAULT, //0
out userToken);
if (!success)
{
throw new SecurityException("Logon user failed");
}
using (WindowsIdentity.Impersonate(userToken))
{
// do the stuff with john.doe's credentials
}