1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
public enum LogonType : int {
LOGON32_LOGON_INTERACTIVE = 2,
LOGON32_LOGON_NETWORK = 3,
LOGON32_LOGON_BATCH = 4,
LOGON32_LOGON_SERVICE = 5,
LOGON32_LOGON_UNLOCK = 7,
LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
LOGON32_LOGON_NEW_CREDENTIALS = 9
};
public enum LogonProvider : int {
LOGON32_PROVIDER_DEFAULT = 0,
LOGON32_PROVIDER_WINNT35 = 1,
LOGON32_PROVIDER_WINNT40 = 2,
LOGON32_PROVIDER_WINNT50 = 3
};
class SecuUtil32 {
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool LogonUser(String lpszUsername,
String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr TokenHandle);
[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);
}
public class NetworkSecurity {
public NetworkSecurity() {
}
public static WindowsImpersonationContext ImpersonateUser
(string strDomain, string strLogin,string strPwd,LogonType
logonType, LogonProvider logonProvider) {
IntPtr tokenHandle = new IntPtr(0);
IntPtr dupeTokenHandle = new IntPtr(0);
try {
const int SecurityImpersonation = 2;
tokenHandle = IntPtr.Zero;
dupeTokenHandle = IntPtr.Zero;
bool returnValue = SecuUtil32.LogonUser(
strLogin,
strDomain,
strPwd,
(int)logonType,
(int)logonProvider,
ref tokenHandle);
if (returnValue == false) {
int ret = Marshal.GetLastWin32Error();
string strErr = String.Format("LogonUser failed with error code : {0}", ret);
throw new ApplicationException(strErr, null);
}
bool retVal = SecuUtil32.DuplicateToken(tokenHandle,
SecurityImpersonation, ref dupeTokenHandle);
if (false == retVal == false) {
SecuUtil32.CloseHandle(tokenHandle);
throw new ApplicationException(
"Failed to duplicate token", null);
}
WindowsIdentity newId = new WindowsIdentity
(dupeTokenHandle);
WindowsImpersonationContext impersonatedUser =
newId.Impersonate();
return impersonatedUser;
} catch (Exception ex) {
throw new ApplicationException(ex.Message, ex);
}
}
} |
Partager