实例介绍
【实例截图】
【核心代码】
using System;
using System.DirectoryServices;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Data;
using System.Diagnostics;
using System.Windows.Forms;
using System.Threading;
///
/// 活动目录辅助类。封装一系列活动目录操作相关的方法。
///
public class ADHelper
{
///
/// 用户登录验证结果
///
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
{
///
/// 登录脚本标志。如果通过 ADSI LDAP 进行读或写操作时,该标志失效。如果通过 ADSI WINNT,该标志为只读。
///
ADS_UF_SCRIPT = 0X0001,
///
/// 用户帐号禁用标志
///
ADS_UF_ACCOUNTDISABLE = 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_PASSWORD_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,
///
/// MNS 帐号标志
///
ADS_UF_MNS_LOGON_ACCOUNT = 0X20000,
///
/// 交互式登录必须使用智能卡
///
ADS_UF_SMARTCARD_REQUIRED = 0X40000,
///
/// 当设置该标志时,服务帐号(用户或计算机帐号)将通过 Kerberos 委托信任
///
ADS_UF_TRUSTED_FOR_DELEGATION = 0X80000,
///
/// 当设置该标志时,即使服务帐号是通过 Kerberos 委托信任的,敏感帐号不能被委托
///
ADS_UF_NOT_DELEGATED = 0X100000,
///
/// 此帐号需要 DES 加密类型
///
ADS_UF_USE_DES_KEY_ONLY = 0X200000,
///
/// 不要进行 Kerberos 预身份验证
///
ADS_UF_DONT_REQUIRE_PREAUTH = 0X4000000,
///
/// 用户密码过期标志
///
ADS_UF_PASSWORD_EXPIRED = 0X800000,
///
/// 用户帐号可委托标志
///
ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0X1000000
}
private DirectoryEntry entry;
public ADHelper(string ADPath, string ADUser, string ADPassword)
{
entry = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);
}
#region GetDirectoryEntry
///
/// 根据用户公共名称和密码取得用户的 对象。
///
/// 用户公共名称
/// 用户密码
/// 如果找到该用户,则返回用户的 对象;否则返回 null
public DirectoryEntry GetDirectoryEntry(string commonName)
{
DirectorySearcher deSearch = new DirectorySearcher(entry);
deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" commonName "))";
deSearch.SearchScope = SearchScope.Subtree;
try
{
SearchResult result = deSearch.FindOne();
entry = new DirectoryEntry(result.Path);
return entry;
}
catch
{
return null;
}
}
///
/// 根据用户帐号称取得用户的 对象
///
/// 用户帐号名
/// 如果找到该用户,则返回用户的 对象;否则返回 null
public DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName)
{
DirectorySearcher deSearch = new DirectorySearcher(entry);
deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" sAMAccountName "))";
deSearch.SearchScope = SearchScope.Subtree;
try
{
SearchResult result = deSearch.FindOne();
entry = new DirectoryEntry(result.Path);
return entry;
}
catch
{
return null;
}
}
///
/// 根据用户帐号和密码取得用户的 对象
///
/// 用户帐号名
/// 用户密码
/// 如果找到该用户,则返回用户的 对象;否则返回 null
public DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName, string password)
{
if (entry != null)
{
string commonName = entry.Properties["cn"][0].ToString();
if (GetDirectoryEntry(commonName) != null)
return GetDirectoryEntry(commonName);
else
return null;
}
else
{
return null;
}
}
///
/// 根据组名取得用户组的 对象
///
/// 组名
///
public DirectoryEntry GetDirectoryEntryOfGroup(string groupName)
{
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);
return entry;
}
catch
{
return null;
}
}
#endregion
#region GetProperty
///
/// 获得指定 指定属性名对应的值
///
///
/// 属性名称
/// 属性值
public static string GetProperty(DirectoryEntry de, string propertyName)
{
if (de.Properties.Contains(propertyName))
{
return de.Properties[propertyName][0].ToString();
}
else
{
return string.Empty;
}
}
///
/// 获得指定搜索结果 中指定属性名对应的值
///
///
/// 属性名称
/// 属性值
public static string GetProperty(SearchResult searchResult, string propertyName)
{
if (searchResult.Properties.Contains(propertyName))
{
return searchResult.Properties[propertyName][0].ToString();
}
else
{
return string.Empty;
}
}
#endregion
///
/// 设置指定 的属性值
///
///
/// 属性名称
/// 属性值
public static void SetProperty(DirectoryEntry de, string propertyName, string propertyValue)
{
if (propertyValue != string.Empty || propertyValue != "" || propertyValue != null)
{
if (de.Properties.Contains(propertyName))
{
de.Properties[propertyName][0] = propertyValue;
}
else
{
de.Properties[propertyName].Add(propertyValue);
}
}
}
///
/// 创建新的用户
///
/// DN 位置。例如:OU=共享平台 或 CN=Users
/// 公共名称
/// 帐号
/// 密码
///
public bool ADD(IdentityImpersonation impersonate, string ldapDN, string user, string displayName, string password)
{
DirectoryEntry subEntry = entry.Children.Find(ldapDN);
DirectoryEntry deUser = subEntry.Children.Add("CN=" user, "user");
deUser.Properties["displayName"].Value = displayName;
deUser.Properties["samAccountName"].Value = user;
deUser.CommitChanges();
SetPassword(impersonate, deUser, password);
EnableUser(impersonate, deUser);
return true;
}
public bool ADD(IdentityImpersonation impersonate, string ldapDN, DataTable dt, ProgressBar progressBar1)
{
progressBar1.Maximum = dt.Rows.Count;
DirectoryEntry subEntry = entry.Children.Find(ldapDN);
foreach (DataRow dr in dt.Rows)
{
progressBar1.Value ;
string user = dr["user"].NullableToString();
string displayName = dr["displayName"].NullableToString();
string password = dr["password"].NullableToString();
DirectoryEntry deUser = subEntry.Children.Add("CN=" user, "user");
deUser.Properties["displayName"].Value = displayName;
deUser.Properties["samAccountName"].Value = user;
deUser.CommitChanges();
SetPassword(impersonate, deUser, password);
EnableUser(impersonate, deUser);
}
return true;
}
public bool ADD(IdentityImpersonation impersonate, DataTable dt, ProgressBar progressBar1,Form f)
{
f.BeginInvoke((ThreadStart)delegate()
{
Stopwatch wath = new Stopwatch();
wath.Start();
DirectoryEntry subEntry = entry.Children.Find("CN=Users");
int addcount = 0;
progressBar1.Maximum = dt.Rows.Count;
foreach (DataRow dr in dt.Rows)
{
progressBar1.Value ;
string user = dr["登录名"].NullableToString();
string displayName = dr["显示名"].NullableToString();
string password = dr["密码"].NullableToString();
if (string.IsNullOrEmpty(user))
continue;
if (string.IsNullOrEmpty(password))
password = user;
DirectoryEntry deUser = subEntry.Children.Add("CN=" user, "user");
deUser.Properties["displayName"].Value = displayName;
deUser.Properties["samAccountName"].Value = user;
deUser.CommitChanges();
SetPassword(impersonate, deUser, password);
EnableUser(impersonate, deUser);
addcount ;
Application.DoEvents();
}
wath.Stop();
decimal runtime = wath.ElapsedMilliseconds;
MessageBox.Show("用时" runtime / 1000 "秒,共导入" addcount "个");
});
return true;
}
///
/// 创建新的用户。默认创建在 Users 单元下。
///
/// 公共名称
/// 帐号
/// 密码
///
public bool ADD(IdentityImpersonation impersonate, string user, string displayName, string password)
{
return ADD(impersonate, "CN=Users", user, displayName, password);
}
///
/// 判断指定公共名称的用户是否存在
///
/// 用户公共名称
/// 如果存在,返回 true;否则返回 false
public bool IsUserExists(string commonName)
{
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;
}
public DataTable SearchAll(string Class)
{
DirectorySearcher deSearch = new DirectorySearcher(entry);
deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user)))";
SearchResultCollection results = deSearch.FindAll();
DataTable dt = new DataTable();
dt.Columns.Add("登录名");
dt.Columns.Add("显示名");
dt.Columns.Add("是否禁用");
dt.Columns.Add("状态");
if (results.Count==0)
return dt;
foreach (SearchResult sr in results)
{
DirectoryEntry de = sr.GetDirectoryEntry();
if (de.Properties["userAccountControl"].Value.NullableToInt() != 514)
if (de.Properties["userAccountControl"].Value.NullableToInt() != 66080)
dt.Rows.Add(de.Name.Substring(3, de.Name.Length-3), de.Properties["displayName"].Value,
de.Properties["primaryGroupID"].Value, de.Properties["userAccountControl"].Value
);
}
return dt;
}
///
/// 判断用户帐号是否激活
///
/// 用户帐号属性控制器
/// 如果用户帐号已经激活,返回 true;否则返回 false
public static bool IsAccountActive(int userAccountControl)
{
int userAccountControl_Disabled = Convert.ToInt32(ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE);
int flagExists = userAccountControl & userAccountControl_Disabled;
if (flagExists > 0)
return false;
else
return true;
}
///
/// 判断用户与密码是否足够以满足身份验证进而登录
///
/// 用户公共名称
/// 密码
/// 如能可正常登录,则返回 true;否则返回 false
public LoginResult Login(string commonName, string password)
{
if (entry != null)
{
// 必须在判断用户密码正确前,对帐号激活属性进行判断;否则将出现异常。
int userAccountControl = Convert.ToInt32(entry.Properties["userAccountControl"][0]);
if (!IsAccountActive(userAccountControl))
return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
if (GetDirectoryEntry(commonName) != null)
return LoginResult.LOGIN_USER_OK;
else
return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;
}
else
{
return LoginResult.LOGIN_USER_DOESNT_EXIST;
}
}
///
/// 判断用户帐号与密码是否足够以满足身份验证进而登录
///
/// 用户帐号
/// 密码
/// 如能可正常登录,则返回 true;否则返回 false
public LoginResult LoginByAccount(string sAMAccountName, string password)
{
if (entry != null)
{
// 必须在判断用户密码正确前,对帐号激活属性进行判断;否则将出现异常。
int userAccountControl = Convert.ToInt32(entry.Properties["userAccountControl"][0]);
if (!IsAccountActive(userAccountControl))
return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
if (GetDirectoryEntryByAccount(sAMAccountName, password) != null)
return LoginResult.LOGIN_USER_OK;
else
return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;
}
else
{
return LoginResult.LOGIN_USER_DOESNT_EXIST;
}
}
///
/// 设置用户密码,管理员可以通过它来修改指定用户的密码。
///
/// 用户公共名称
/// 用户新密码
public void SetPassword(IdentityImpersonation impersonate, DirectoryEntry deUser, string newPassword)
{
impersonate.BeginImpersonate();
deUser.Invoke("SetPassword", new object[] { newPassword });
impersonate.StopImpersonate();
}
///
/// 设置帐号密码,管理员可以通过它来修改指定帐号的密码。
///
/// 用户帐号
/// 用户新密码
public void SetPasswordByAccount(IdentityImpersonation impersonate, string sAMAccountName, string newPassword)
{
//IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);
impersonate.BeginImpersonate();
entry.Invoke("SetPassword", new object[] { newPassword });
impersonate.StopImpersonate();
}
///
/// 修改用户密码
///
/// 用户公共名称
/// 旧密码
/// 新密码
public void ChangeUserPassword(string commonName, string oldPassword, string newPassword)
{
// to-do: 需要解决密码策略问题
DirectoryEntry oUser = GetDirectoryEntry(commonName);
oUser.Invoke("ChangePassword", new Object[] { oldPassword, newPassword });
}
/////
///// 启用指定公共名称的用户
/////
///// 用户公共名称
//public void EnableUser(IdentityImpersonation impersonate, string commonName)
//{
// EnableUser(impersonate, GetDirectoryEntry(commonName));
//}
///
/// 启用指定 的用户
///
///
public void EnableUser(IdentityImpersonation impersonate, DirectoryEntry de)
{
impersonate.BeginImpersonate();
de.Properties["userAccountControl"][0] = ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD;
de.CommitChanges();
impersonate.StopImpersonate();
}
///
/// 禁用指定公共名称的用户
///
/// 用户公共名称
public void DisableUser(IdentityImpersonation impersonate, string commonName)
{
DisableUser(impersonate, GetDirectoryEntry(commonName));
}
///
/// 禁用指定 的用户
///
///
public void DisableUser(IdentityImpersonation impersonate, DirectoryEntry de)
{
impersonate.BeginImpersonate();
de.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_ACCOUNTDISABLE;
de.CommitChanges();
impersonate.StopImpersonate();
}
///
/// 将指定的用户添加到指定的组中。默认为 Users 下的组和用户。
///
/// 用户公共名称
/// 组名
public void AddUserToGroup(IdentityImpersonation impersonate, string userCommonName, string groupName)
{
DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);
DirectoryEntry oUser = GetDirectoryEntry(userCommonName);
impersonate.BeginImpersonate();
oGroup.Properties["member"].Add(oUser.Properties["distinguishedName"].Value);
oGroup.CommitChanges();
impersonate.StopImpersonate();
}
///
/// 将用户从指定组中移除。默认为 Users 下的组和用户。
///
/// 用户公共名称
/// 组名
public void RemoveUserFromGroup(IdentityImpersonation impersonate, string userCommonName, string groupName)
{
DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);
DirectoryEntry oUser = GetDirectoryEntry(userCommonName);
impersonate.BeginImpersonate();
oGroup.Properties["member"].Remove(oUser.Properties["distinguishedName"].Value);
oGroup.CommitChanges();
impersonate.StopImpersonate();
}
}
///
/// 用户模拟角色类。实现在程序段内进行用户角色模拟。
///
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;
///
/// 构造函数
///
/// 所要模拟的用户的用户名
/// 所要模拟的用户的密码
/// 所要模拟的用户所在的域
public IdentityImpersonation(String impersonationDomain, String impersonationUsername, String impersonationPassword)
{
_sImperUsername = impersonationUsername;
_sImperPassword = impersonationPassword;
_sImperDomain = impersonationDomain;
_adminToken = IntPtr.Zero;
_dupeToken = IntPtr.Zero;
_bClosed = true;
}
///
/// 析构函数
///
~IdentityImpersonation()
{
if (!_bClosed)
{
StopImpersonate();
}
}
///
/// 开始身份角色模拟。
///
///
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;
}
///
/// 停止身分角色模拟。
///
public void StopImpersonate()
{
if (_imperContext == null)
return;
_imperContext.Undo();
CloseHandle(_dupeToken);
CloseHandle(_adminToken);
_bClosed = true;
}
}
标签: 域账号 管理
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论