如果希望使用C#進行後臺域登錄,需要使用到advapi32.dll這個程序集。advapi32.dll是一個高級API應用程序接口服務庫的一部分,包含的函數與對象的安全性,註冊表的操控以及事件日誌有關。xp系統一般位於C:\WINDOWS\system32\目錄下,大小659KB。
下面是實現域登錄的代碼:
public class SimulateDomainService
{
public static bool ImpersonateValidUser(String userName, String domain, String password)
{
//ServiceContext.SetThreadPrincipal();
WindowsImpersonationContext impersonationContext;
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}
/// <summary>
/// 模擬登錄
/// </summary>
/// <returns></returns>
public static bool ImpersonateValidUser()
{
return ImpersonateValidUser(GetValue("account"), GetValue("domain"), GetValue("pwd"));
}
/// <summary>
/// 讀取指定key的值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetValue(string key)
{
return System.Configuration.ConfigurationManager.AppSettings[key].ToString();
}
public static CustomReportCredentials GetReportCredentials(String account,String domain,String pwd)
{
return new CustomReportCredentials(account, pwd, domain);
}
/// <summary>
/// 獲取報表認證信息
/// </summary>
/// <returns></returns>
public static CustomReportCredentials GetReportCredentials()
{
return GetReportCredentials(GetValue("account"), GetValue("domain"), GetValue("pwd"));
}
#region win32 api extend method
[DllImport("advapi32.dll")]
static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern bool CloseHandle(IntPtr handle);
const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_PROVIDER_DEFAULT = 0;
#endregion
}
其中:
ImpersonateValidUser
這個方法有三個參數,分別是賬戶名、域名、密碼。返回值是boole型,如果返回true則說明登錄成功,否則登錄失敗。
注意:服務器需要在模擬登錄的域名之內(屬於同一域)