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 ?
Impersonation is the process of assigning a user account to an unknown user.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With