WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();
...
context.Undo();
我在哪里申报管理员用户名和密码?用用户名和密码模拟?
的的accessToken PARAM并不能帮助我太多...
我必须导入DLL的呢?
WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();
...
context.Undo();
我在哪里申报管理员用户名和密码?用用户名和密码模拟?
的的accessToken PARAM并不能帮助我太多...
我必须导入DLL的呢?
你需要得到用户的令牌这里) 在c#
外部方法声明,想象它在C#中。使用P /从ADVAPI32.DLL调用LogonUser
:
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
out IntPtr phToken);
例子:
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
}
您需要P /调用LogonUser()
API。接受用户名,域名和密码并返回一个令牌。
它正是你必须使用的accesstoken。要得到它,你需要调用LogonUser方法:
oops没有意识到,我只是在这里的VB.net代码。
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
和执行:
_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()
有什么办法没有密码这样做呢?我有权访问它,因为我在模仿之前就开始创作,只是想我会问。 – Doug
我想应该调用'CloseHandle'(正如[LogonUser'文档中所述](https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v = vs.85) .aspx))为使用块之后的'userToken'。或者这是由'WindowsIdentity'以某种方式调用的? – CodeFox
嗨如果这是ASP.NET应用程序,这是什么范围? 我应该在每一页中调用这个函数吗? –