using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
namespace TemperatureTest
{
public sealed class ADHelper
{
private static string m_DomainName = "MyDomain"; //域名
private static string m_LDAPDomain = "DC=MyDomain,DC=local"; //LDAP地址
private static string m_ADPath = "LDAP://brooks.mydomain.local"; //LDAP绑定路径
private static string m_ADUser = "Administrator"; //登录帐号
private static string m_ADPassword = "password"; //登录密码
private static IdentityImpersonation m_impersonate = new IdentityImpersonation(m_ADUser, m_ADPassword, m_DomianName); //创建扮演类的实例
//用户登录验证结果
public enum LoginResult
{
LOGIN_USER_OK = 0, //用户正常登录
LOGIN_USER_DOESNT_EXIST, //用户不存在
LOGIN_USER_ACCOUNT_INACTIVE, //用户帐号被禁用
LOGIN_USER_PASSWORD_INCORRECT //用户密码不正确
}
//用户属性定义标志
public enum ADS_USER_FLAG_ENUM
{
ADS_UF_SCRIPT = 0X0001, //登录脚本标志(如果通过ADSI LDAP进行读、写操作时,该标志失效。如果通过ADSI WINNT,该标志只读)
ADS_UF_ACCOUNT_DISABLE = 0X0002, //用户帐号禁用标志
ADS_UF_HOMEDIR_REQUIRED = 0X0008, //主文件夹标志
ADS_UF_LOCKOUT = 0X0010, //过期标志
ADS_UF_PASSWD_NOTREQD = 0X0020, //用户密码不是必须的
ADS_UF_PASSWD_CANT_CHANGE = 0X0040, //用户密码不能更改标志
ADS_UF_ENCRYPTED_TEXT_PASSWD_ALLOWED = 0X0080, //使用可逆的加密保存密码
ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0X0100, //本地帐号标志
ADS_UF_NORMAL_ACCOUNT = 0X0200, //普通用户的默认帐号类型
ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 0X0800, //跨域的信任帐号标志
ADS_UF_WORKSTATION_TRUST_ACCOUNT = 0X1000, //工作站信任帐号标志
ADS_UF_SERVER_TRUST_ACCOUNT = 0X2000, //服务器信任帐号标志
ADS_UF_DONT_EXPIRE_PASSWD = 0X10000, //密码永不过期标志
ADS_UF_MNS_LOGON_ACCOUNT = 0X20000, //MNS帐号标志
ADS_UF_SMARTCARD_REQUIRED = 0X40000, //交互式登录必须使用智能卡标志
ADS_UF_TRUSTED_FOR_DELEGATION = 0X80000, //当设置该标志时,服务帐号(用户OR计算机帐号)将通过Kerberos委托信任
ADS_UF_NOT_DELEGATED = 0X100000, //当设置该标志时,即使服务帐号是通过Kerberos委托信任的,但敏感帐号不能被委托
ADS_UF_USE_DES_KEY_ONLY = 0X200000, //此帐号需要DES加密类型
ADS_UF_DONT_REQUIRE_PREAUTH = 0X400000, //不需要进行Kerberos预身份验证
ADS_UF_PASSWORD_EXPIRED = 0X800000, //用户密码过期标志
ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0X1000000 //用户帐号可委托标志
}
//构造函数
public ADHelper()
{
}
#region 获取DirectroyEntry对象实例的方法及重载
/// <summary>
/// 获取DirectoryEntry对象实例并以管理员登录AD
/// </summary>
/// <param name="">无</param>
/// <returns>返回DirectoryEntry对象实例</returns>
private static DirectoryEntry GetDirectoryObject()
{
DirectoryEntry entry = new DirectoryEntry(m_ADPath, m_ADUser, m_ADPassword, AuthenticationTypes.Secure);
return entry;
}
/// <summary>
/// 根据指定用户名和密码获取相应的DirectoryEntry实例
/// </summary>
/// <param name="userName,password">用户名、密码</param>
/// <returns>返回DirectoryEntry对象实例</returns>
private static DirectoryEntry GetDirectoryObject(string userName, string password)
{
DirectoryEntry entry = new DirectoryEntry(m_ADPath, userName, password);
return entry;
}
/// <summary>
/// 根据指定域获取相应的DirectoryEntry实例
/// </summary>
/// <param name="domainReference">涉及域</param>
/// <returns>返回DirectoryEntry对象实例</returns>
private static DirectoryEntry GetDirectoryObject(string domainReference)
{
DirectoryEntry entry = new DirectoryEntry(m_ADPath + domainReference, m_ADUser, m_ADPassword, AuthenticationTypes.Secure);
return entry;
}
/// <summary>
/// 获得以UserName,Password创建的DirectoryEntry对象实例
/// </summary>
/// <param name="domainReference,userName,password">涉及域、用户名、密码</param>
/// <returns>返回DirectoryEntry对象实例</returns>
private static DirectoryEntry GetDirectoryObject(string domainReference, string userName, string password)
{
DirectoryEntry entry = new DirectoryEntry(m_ADPath + domainReference, userName, password, AuthenticationTypes.Secure);
return entry;
}
#endregion
#region 获取DirectoryEntry 用户的对象的方法及重载
/// <summary>
/// 根据用户的公共名称取得用户的对象
/// </summary>
/// <param name="commonName">用户的公共名</param>
/// <returns>返回DirectoryEntry对象实例</returns>
public static DirectoryEntry GetDirectoryEntry(string commonName)
{
DirectoryEntry adminEntry = GetDirectoryObject();
DirectorySearcher adminSearch = new DirectorySearcher(adminEntry);
adminSearch.Filter = "(&(&(objectCategory = person)(objectClass = user))(cn = " + commonName + "))";
adminSearch.SearchScope = SearchScope.Subtree;
try
{
SearchResult result = adminSearch.FindOne();
adminEntry = new DirectoryEntry(result.Path);
return adminEntry;
}
catch
{
return null;
}
}
/// <summary>
/// 根据用户公共名称和密码取得用户的对象
/// </summary>
/// <param name="commonName,password">用户公共名、密码</param>
/// <returns>返回DirectroyEntry对象实例</returns>
public static DirectoryEntry GetDirectoryEntry(string commonName, string password)
{
DirectoryEntry entry = GetDirectoryObject(commonName, password);
DirectorySearcher commonSearch = new DirectorySearcher(entry);
commonSearch.Filter - "(&(&(objectCategory = person)(objectClass = user))(cn = " + commonName + "))";
commonSearch.SearchScope = SearchScope.Subtree;
try
{
SearchResult result = commonSearch.FindOne();
entry = new DirectoryEntry(result.Path);
return entry;
}
catch
{
return null;
}
}
/// <summary>
/// 根据用户帐号取得用户的对象
/// </summary>
/// <param name="userAccountName">用户帐号名</param>
/// <returns>返回DirectroyEntry对象实例</returns>
public static DirectoryEntry GetDirectoryEntryByAccount(string userAccountName)
{
DirectoryEntry entry = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher(entry);
deSearch.Filter = "(&(&(objectCategory = person)(objectClass = user))(userAccountName = " + userAccountName + "))";
deSearch.SearchScope = SearchScope.Subtree;
try
{
SearchResult result = deSearch.FindOne();
entry = new DirectoryEntry(result.Path);
return entry;
}
catch
{
return null;
}
}
/// <summary>
/// 根据用户帐号和密码取得用户的对象
/// </summary>
/// <param name="userAccountName,password">用户帐号、密码</param>
/// <returns>返回DirectoryEntry对象实例</returns>
public static DirectoryEntry GetDirectoryEntryByAccount(string userAccountName, string password)
{
DirectoryEntry entry = GetDirectoryEntryByAccount(userAccountName);
if (entry != null)
{
string commonName = entry.Properties["cn"][0].ToString();
if (GetDirectoryEntry(commonName, password) != null)
{
return GetDirectoryEntry(commonName, password);
}
else
{
return null;
}
}
else
{
return null;
}
}
/// <summary>
/// 根据组名取得用户组的对象
/// </summary>
/// <param name="groupName">组名</param>
/// <returns>返回DirectoryEntry对象实例</returns>
public static DirectoryEntry GetDirectoryEntryByGroup(string groupName)
{
DirectoryEntry entry = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher(entry);
deSearch.Filter = "(&(objectClass = group)(cn =" + groupName + "))";
deSearch.SearchScope = SearchScope.Subtree;
try
{
SearchResult result = deSearch.FindOne();
entry = new DirectoryEntry(result.Path);
}
catch
{
return null;
}
}
#endregion
#region 获取属性值的方法及重载
/// <summary>
/// 获取指定的属性名对应的值
/// </summary>
/// <param name="entry,propertyName">DirectoryEntry对象实例、属性名</param>
/// <returns>返回属性值(字符串类型)</returns>
public static string GetProperty(DirectoryEntry entry, string propertyName)
{
if (entry.Properties.Contains(propertyName))
{
return entry.Properties[propertyName][0].ToString();
}
else
{
return string.Empty;
}
}
/// <summary>
/// 获取指定搜索结果中的属性名对应的值
/// </summary>
/// <param name="searchResult,propertyName">搜索的结果(SearchResult类型的对象实例),属性名</param>
/// <returns>返回string 类型的属性值</returns>
public static string GetProperty(SearchResult searchResult, string propertyName)
{
if (searchResult.Properties.Contains(propertyName))
{
return searchResult.Properties[propertyName][0].ToString();
}
else
{
return string.Empty;
}
}
#endregion
/// <summary>
/// 设置指定的属性值
/// </summary>
/// <param name="entry,propertyName,propertyValue">DirectoryEntry对象实例,属性名,属性值</param>
/// <returns>无</returns>
public static void SetProperty(DirectoryEntry entry,string propertyName,string propertyValue)
{
if (propertyValue != string.Empty || propertyValue != "" || propertyValue != null)
{
if (entry.Properties.Contains(propertyName))
{
entry.Properties[propertyName][0] = propertyValue;
}
else
{
entry.Properties[propertyName].Add(propertyValue);
}
}
}
#region 创建新的用户的方法及重载
/// <summary>
/// 创建新的用户
/// </summary>
/// <param name="ldapDN,commonName,userAccountName,password">LDAP的DN位置,公共名,用户帐号,密码</param>
/// <returns>返回DirectoryEntry对象实例</returns>
public static DirectoryEntry CreateNewUser(string ldapDN, string commonName, string userAccountName, string password)
{
DirectoryEntry entry = GetDirectoryObject();
DirectoryEntry subEntry = entry.Children.Find(ldapDN);
DirectoryEntry deUser = subEntry.Children.Add("CN=" + commonName, "user");
deUser.Properties["userAccountName"].Value = userAccountName;
deUser.CommitChanges();
ADHelper.EnableUser(commonName);
ADHelper.SetPassword(commonName, password);
deUser.Close();
return deUser;
}
/// <summary>
/// 创建新的用户(重载)
/// </summary>
/// <param name="commonName,userAccountName,password">公共名,用户帐号,密码</param>
/// <returns>返回DirectoryEntry对象实例</returns>
public static DirectoryEntry CreateNewUser(string commonName, string userAccountName, string password)
{
return CreateNewUser("CN=Users", commonName, userAccountName, password);
}
#endregion
/// <summary>
/// 判断指定公共名称的用户是否存在
/// </summary>
/// <param name="commonName">公共名称</param>
/// <returns>如果存在,返回true;否则返回false</returns>
public static bool IsUserExists(string commonName)
{
DirectoryEntry entry = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher(entry);
deSearch.Filter = "(&(&(objectCategory = person)(objectClass=user))(cn=" + commonName + "))";
//LDAP查询串
SearchResultCollection results = deSearch.FindAll();
if (results.Count == 0)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 判断用户帐号是否激活
/// </summary>
/// <param name="userAccountControl">用户帐号属性控制奇</param>
/// <returns>如果帐号已激活,返回true;否则false</returns>
public static bool IsAccountActive(int userAccountContol)
{
int userAccountControl_Disabled = Convert.ToInt32(ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNT_DISABLE);
int flagExists = userAccountContol & userAccountControl_Disabled;
if (flagExists>0)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 判断用户与密码是否足够以满足身份验证进而登录
/// </summary>
/// <param name="commonName,password">用户公共名称,密码</param>
/// <returns>如能正常登录,则返回true;否则返回false</returns>
public static LoginResult Login(string commonName, string password)
{
DirectoryEntry entry = GetDirectoryEntry(commonName);
if (entry != null)
{
//必须在判断用户密码正确前,对帐号激活属性进行判断;否则将出现异常
int userAccountControl = Convert.ToInt32(entry.Properties["userAccountControl"][0]);
entry.Close();
if (!IsAccountActive(userAccountControl))
{
return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
}
if (GetDirectoryEntry(commonName, password) != null)
{
return LoginResult.LOGIN_USER_OK;
}
else
{
return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;
}
}
else
{
return LoginResult.LOGIN_USER_DOESNT_EXIST;
}
}
/// <summary>
/// 判断用户帐号与密码是否足够以满足身份验证进而登录
/// </summary>
/// <param name="userAccountName,password">用户帐号,密码</param>
/// <returns>如能正常登录,返回true;否则返回false</returns>
public static LoginResult LoginByAccount(string userAccountName, string password)
{
DirectoryEntry entry = GetDirectoryEntryByAccount(userAccountName);
if (entry != null)
{
//必须在判断用户密码正确前,对帐号激活属性进行判断;否则将出现异常
int userAccountControl = Convert.ToInt32(entry.Properties["userAccountControl"][0]);
entry.Close();
if (!IsAccountActive(userAccountControl))
{
return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
}
if (GetDirectoryEntryByAccount(userAccountName, password) != null)
{
return LoginResult.LOGIN_USER_OK;
}
else
{
return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;
}
}
else
{
return LoginResult.LOGIN_USER_DOESNT_EXIST;
}
}
/// <summary>
/// 设置用户密码(管理员可以通过它修改指定用户的密码)
/// </summary>
/// <param name="commonName,newPassword">用户公共名称,用户新密码</param>
/// <returns>无</returns>
public static void SetPassword(string commonName, string newPassword)
{
DirectoryEntry entry = GetDirectoryEntry(commonName);
//模拟超级管理员,以达到有权限修改用户密码
impersonate.BeginImpersonate();
entry.Invoke("SetPassword",new object []{newPassword});
impersonate.StopImpersonate();
entry.Close();
}
/// <summary>
/// 设置帐号密码(管理员可以通过它来修改指定帐号的密码)
/// </summary>
/// <param name="userAccountName,newpassword">用户帐号,用户新密码</param>
/// <returns>无</returns>
public static void SetPasswordByAccount(string userAccountName, string newpassword)
{
DirectoryEntry entry = GetDirectoryEntryByAccount(userAccountName);
//模拟超级管理员,以达到有权限修改用户密码
IdentityImpersonation impersonate = new IdentityImpersonation(m_ADUser, m_ADPassword, m_DomianName);
impersonate.BeginImpersonate();
entry.Invoke("SetPassword", new object[] { newpassword });
impersonate.StopImpersonate();
entry.Close();
}
/// <summary>
/// 修改用户密码
/// </summary>
/// <param name="commonName,oldPassword,newPassword">用户公共名称,旧密码,新密码</param>
/// <returns>无</returns>
public static void ChangeUserPassword(string commonName, string oldPassword, string newPassword)
{
//需要解决密码策略问题
DirectoryEntry entry = GetDirectoryEntry(commonName);
entry.Invoke("ChangePassword", new object[] { oldPassword, newPassword });
entry.Close();
}
/// <summary>
/// 启用指定公共名称的用户
/// </summary>
/// <param name="commonName">用户公共名</param>
/// <returns>无</returns>
public static void EnableUser(string commonName)
{
EnableUser(GetDirectoryEntry(commonName));
}
/// <summary>
/// 启用指定的用户
/// </summary>
/// <param name="entry">DirectoryEntry对象实例</param>
/// <returns>无</returns>
public static void EnableUser(DirectoryEntry entry)
{
impersonate.BeginImpersonate();
entry.Properties["userAccountControl"][0] = ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT |
ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD;
entry.CommitChanges();
impersonate.StopImpersonate();
entry.Close();
}
/// <summary>
/// 禁用指定公共名称的用户
/// </summary>
/// <param name="commonName">用户公共名称</param>
/// <returns>无</returns>
public static void DisableUser(string commonName)
{
DisableUser(GetDirectoryEntry(commonName));
}
/// <summary>
/// 禁用指定的用户
/// </summary>
/// <param name="entry">DirectoryEntry对象实例</param>
/// <returns>无</returns>
public static void DisableUser(DirectoryEntry entry)
{
impersonate.BeginImpersonate();
entry.Properties["userAccountControl"][0] = ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT |
ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD |
ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNT_DISABLE;
entry.CommitChanges();
impersonate.stopImpersonate();
entry.Close();
}
/// <summary>
/// 将指定用户添加到指定的组中(默认为Users下的组和用户)
/// </summary>
/// <param name="commonName,groupName">用户公共名称,组名</param>
/// <returns>无</returns>
public static void AddUserToGroup(string commonName, string groupName)
{
DirectoryEntry entryGroup = GetDirectoryEntryByGroup(groupName);
DirectoryEntry entryUser = GetDirectoryEntry(commonName);
impersonate.BeginImpersonate();
entryGroup.Properties["member"].Add(entryUser.Properties["distinguishedName"].Value);
entryGroup.CommitChanges();
impersonate.StopImpersonate();
entryGroup.Close();
entryUser.Close();
}
/// <summary>
/// 将用户从指定组中移除(默认为Users下的组和用户)
/// </summary>
/// <param name="commonName,groupName">用户公共名称,组名</param>
/// <returns>无</returns>
public static void RemoveUserFromGroup(string commonName, string groupName)
{
DirectoryEntry entryGroup = GetDirectoryEntryByGroup(groupName);
DirectoryEntry entryUser = GetDirectoryEntry(commonName);
impersonate.BeginImpersonate();
entryGroup.Properties["member"].Remove(entryUser.Properties["distinguishedName"].Value);
entryGroup.CommitChanges();
impersonate.StopImpersonate();
entryGroup.Close();
entryUser.Close();
}
}
//用户模拟角色类(实现在程序段内进行用户角色模拟)
public class IdentityImpersonation
{
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("advapi32.dll",CharSet = CharSet.Auto,SetLastError = true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,int SECURITY_IMPERSONATION_LEVEL,
ref IntPtr DuplicateTokenHandle);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
//要模拟的用户的用户名、密码、域(机器名)
private string _sImperUsername;
private string _sImperPassword;
private string _sImperDomain;
//记录模拟上下文
private WindowsImpersonationContext _imperContext;
private IntPtr _adminToken;
private IntPtr _dupeToken;
//是否已停止模拟
private Boolean _bClosed;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="impersonationUsername,impersonationPassword,impersonationDomain">所要模拟的用户的用户名、密码、域</param>
/// <returns></returns>
public IdentityImpersonation(string impersonationUsername, string impersonationPassword, string impersonationDomain)
{
_sImperUsername = impersonationUsername;
_sImperPassword = impersonationPassword;
_sImperDomain = impersonationDomain;
_adminToken = IntPtr.Zero;
_dupeToken = IntPtr.Zero;
_bClosed = true;
}
/// <summary>
/// 析构函数
/// </summary>
/// <param name=""></param>
/// <returns></returns>
~IdentityImpersonation()
{
if (!_bClosed)
{
StopImpersonate();
}
}
/// <summary>
/// 开始身份角色模拟
/// </summary>
/// <param name=""></param>
/// <returns></returns>
public Boolean BeginImpersonate()
{
Boolean bLogined = LogonUser(_sImperUsername, _sImperDomain, _sImperPassword, 2, 0, ref _adminToken);
if (!bLogined)
{
return false;
}
Boolean bDuped = DuplicateToken(_adminToken, 2, ref _dupeToken);
if (!bDuped)
{
return false;
}
WindowsIdentity fakeId = new WindowsIdentity(_dupeToken);
_imperContext = fakeId.Impersonate();
_bClosed = false;
return true;
}
/// <summary>
/// 停止身份角色模拟
/// </summary>
/// <param name=""></param>
/// <returns></returns>、
public void StopImpersonate()
{
_imperContext.Undo();
CloseHandle(_dupeToken);
CloseHandle(_adminToken);
_bClosed = true;
}
}
}