in the System.Security see WindowsIdentity.Impersonate and LogonUser and
DuplicateToken in the win32api to get the actual token (using
System.Runtime.InteropServices will allow access to win32 api). as you
will need to call unmanged code, you will full trust set. also impersonate
permission will be required.
air code:
// import win32 api
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool LogonUser(String lpszUsername,
String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider,
ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll",
CharSet=CharSet.Auto, SetLastError=true)]
public extern static bool DuplicateToken(IntPtr
ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL,
ref IntPtr DuplicateTokenHandle);
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
// get logon token
var tokenHandle = new IntPtr(0);
var dupeTokenHandle = new IntPtr(0);
var bImpersonated = LogonUser(
sUsername, sDomain, sPassword,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref pExistingTokenHandle);
// call dup to set proper security tokens
var bRetVal = DuplicateToken(
pExistingTokenHandle,
(int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
ref pDuplicateTokenHandle);
// create new identity using new primary token
var newId = new WindowsIdentity(pDuplicateTokenHandle);
var impersonatedUser = newId.Impersonate();
// do code here
// restore
impersonatedUser.Undo();
CloseHandle(pExistingTokenHandle);
CloseHandle(pDuplicateTokenHandle);
-- bruce (sqlwork.com)
The C# code below throws System.Runtime.InteropServices.COMException
(0x80070005)
when accessing an IIS-server on a different domain/computer where
the current user doesn't have any permissions (de.Chilren isn't allowed).
How can I "log in" programmatically with a different user?
string s = "";
DirectoryEntry de = new DirectoryEntry();
de.Path = "IIS://mywebserver/W3SVC";
foreach (DirectoryEntry site in de.Children)
{
s += site.Properties["ServerComment"] + "\n";
}