Impersonate with username and password?

2019-02-01 14:49发布

问题:

WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();

 ...
context.Undo();

Where do i declare a administraotr UserName and Passowrd ?

the accessToken param doesn't help me too much...

Do I have to import DLL'S for it ?

回答1:

You need to get the user's token. Use the p/invoke LogonUser from the advapi32.dll:

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool LogonUser(
            string lpszUsername,
            string lpszDomain,
            string lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            out IntPtr phToken);

Example:

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
}


回答2:

its exactly the accesstoken you have to use. to get it you need to call the LogonUser method:

oops didnt realise that i just have the VB.net code just here. imagine it in C# ;) here in c#

external method declaration:

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

and the execution:

_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()


回答3:

You need to P/invoke the LogonUser() API. That accepts username, domain and password and returns a token.