标签:
如果希望使用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则说明登录成功,否则登录失败。
注意:服务器需要在模拟登录的域名之内(属于同一域)
标签:
原文地址:http://blog.csdn.net/mx5721/article/details/42708225