Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Impersonate with username and password?

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 ?

like image 434
Royi Namir Avatar asked Oct 10 '11 09:10

Royi Namir


People also ask

What is impersonation in authentication?

Impersonation is the process of assigning a user account to an unknown user.

What is identity impersonate?

Impersonation is the process of executing code in the context of another user identity. By default, all ASP.NET code is executed using a fixed machine-specific account. To execute code using another identity we can use the built-in impersonation capabilities of ASP.NET.

How do I impersonate a user in Windows 10?

To impersonate another user you must first retrieve the security information of the user you want to impersonate, cache that information in a security context structure, and then later use the information in the security context structure to send the impersonated messages.


1 Answers

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
}
like image 123
Stefan Avatar answered Oct 17 '22 03:10

Stefan