C# LDAP 管理(创建新用户)
今天用C#实现了一套LDAP域账号的创建和查询,感受挺多。
算是第一次接触LDAP吧,之前曾经做了一个登录的验证,就是查询功能,那个相对比较简单,用到了一个方法就搞定了。
这次的需求是要用编程的方式创建域账号,实现域登陆。
首先回顾一下之前查询用到的代码:
public static bool TryAuthenticate(string userName, string password)
{
string domain = "litb-inc.com";
bool isLogin = false;
try
{
DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), userName, password);
entry.RefreshCache();
DBLog.Debug("check success");
isLogin = true;
}
catch (Exception ex)
{
DBLog.Debug("域验证抛出异常 :" + ex.Message + ex.InnerException);
isLogin = false;
}
return isLogin;
}
这是验证指定用户是否在域里认证通过。
接下来,实现创建域账户的操作。在网上找到了一个操作类:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.DirectoryServices;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions; namespace Litb.HRExtension
{
//静态AD连接类
public static class AdHerlp
{
#region 创建AD连接
/// <summary>
/// 创建AD连接
/// </summary>
/// <returns></returns>
public static DirectoryEntry GetDirectoryEntry()
{
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://testhr.com/CN=Users,DC=testhr,DC=com";
de.Username = @"administrator";
de.Password = "litb20!!";
return de;
}
#endregion #region 获取目录实体集合(DomainReference传空即可)
/// <summary>
///
/// </summary>
/// <param name="DomainReference"></param>
/// <returns></returns>
public static DirectoryEntry GetDirectoryEntry(string DomainReference)
{
DirectoryEntry entry = new DirectoryEntry("LDAP://testhr.com" + DomainReference, "administrator", "litb20!!", AuthenticationTypes.Secure);
return entry;
}
#endregion
} //AD操作类
public class ADHelper
{
/// <summary>
/// 判断用户是否存在
/// </summary>
/// <param name="UserName"></param>
/// <returns></returns>
public bool UserExists(string UserName)
{
DirectoryEntry de = AdHerlp.GetDirectoryEntry();
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
deSearch.Filter = "(&(objectClass=user) (cn=" + UserName + "))";
SearchResultCollection results = deSearch.FindAll();
if (results.Count == )
{
return false;
}
else
{
return true;
}
} /// <summary>
/// 创建一个新用户
/// </summary>
/// <param name="employeeID"></param>
/// <param name="name"></param>
/// <param name="login"></param>
/// <param name="email"></param>
/// <param name="group"></param>
public void CreateNewUser(string employeeID, string name, string login, string email, string group)
{
DirectoryEntry de = AdHerlp.GetDirectoryEntry(); /// 1. Create user account
DirectoryEntries users = de.Children;
DirectoryEntry newuser = users.Add("CN=" + login, "user"); /// 2. Set properties
SetProperty(newuser, "employeeID", employeeID);
SetProperty(newuser, "givenname", name);
SetProperty(newuser, "SAMAccountName", login);
SetProperty(newuser, "userPrincipalName", login);
SetProperty(newuser, "mail", email);
SetProperty(newuser, "Description", "Create User By HrESS System");
newuser.CommitChanges(); /// 3. Set password
newuser.AuthenticationType = AuthenticationTypes.Secure;
object[] password = new object[] { SetSecurePassword() };
object ret = newuser.Invoke("SetPassword", password);
newuser.CommitChanges(); //SetPassword(newuser);
//newuser.CommitChanges(); /// 4. Enable account
EnableAccount(newuser); /// 5. Add user account to groups
AddUserToGroup(de, newuser, group); /// 6. Create a mailbox in Microsoft Exchange
//GenerateMailBox(login); newuser.Close();
de.Close();
} /// <summary>
/// 修改用户属性
/// </summary>
/// <param name="de"></param>
/// <param name="PropertyName"></param>
/// <param name="PropertyValue"></param>
public static void SetProperty(DirectoryEntry de, string PropertyName, string PropertyValue)
{
if (PropertyValue != null)
{
if (de.Properties.Contains(PropertyName))
{
de.Properties[PropertyName][] = PropertyValue;
}
else
{
de.Properties[PropertyName].Add(PropertyValue);
}
}
} /// <summary>
/// 生成随机密码
/// </summary>
/// <returns></returns>
public string SetSecurePassword()
{
return "qwe123!@#";
} /// <summary>
/// 设置用户新密码
/// </summary>
/// <param name="path"></param>
public void SetPassword(DirectoryEntry newuser)
{
newuser.AuthenticationType = AuthenticationTypes.Secure;
object[] password = new object[] { SetSecurePassword() };
object ret = newuser.Invoke("SetPassword", password);
newuser.CommitChanges();
newuser.Close();
} /// <summary>
/// 启用用户帐号
/// </summary>
/// <param name="de"></param>
private static void EnableAccount(DirectoryEntry de)
{
//UF_DONT_EXPIRE_PASSWD 0x10000
int exp = (int)de.Properties["userAccountControl"].Value;
de.Properties["userAccountControl"].Value = exp | 0x0001;
de.CommitChanges();
//UF_ACCOUNTDISABLE 0x0002
int val = (int)de.Properties["userAccountControl"].Value;
de.Properties["userAccountControl"].Value = val & ~0x0002;
de.CommitChanges();
} /// <summary>
/// 添加用户到组
/// </summary>
/// <param name="de"></param>
/// <param name="deUser"></param>
/// <param name="GroupName"></param>
public static void AddUserToGroup(DirectoryEntry de, DirectoryEntry deUser, string GroupName)
{
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
deSearch.Filter = "(&(objectClass=group) (cn=" + GroupName + "))";
SearchResultCollection results = deSearch.FindAll(); bool isGroupMember = false; if (results.Count > )
{
DirectoryEntry group = AdHerlp.GetDirectoryEntry(results[].Path); object members = group.Invoke("Members", null);
foreach (object member in (IEnumerable)members)
{
DirectoryEntry x = new DirectoryEntry(member);
if (x.Name != deUser.Name)
{
isGroupMember = false;
}
else
{
isGroupMember = true;
break;
}
} if (!isGroupMember)
{
group.Invoke("Add", new object[] { deUser.Path.ToString() });
}
group.Close();
}
return;
} /// <summary>
/// 禁用一个帐号
/// </summary>
/// <param name="EmployeeID"></param>
public void DisableAccount(string EmployeeID)
{
DirectoryEntry de = AdHerlp.GetDirectoryEntry();
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&(objectCategory=Person)(objectClass=user)(employeeID=" + EmployeeID + "))";
ds.SearchScope = SearchScope.Subtree;
SearchResult results = ds.FindOne(); if (results != null)
{
DirectoryEntry dey = AdHerlp.GetDirectoryEntry(results.Path);
int val = (int)dey.Properties["userAccountControl"].Value;
dey.Properties["userAccountControl"].Value = val | 0x0002;
dey.Properties["msExchHideFromAddressLists"].Value = "TRUE";
dey.CommitChanges();
dey.Close();
} de.Close();
} /// <summary>
/// 修改用户信息
/// </summary>
/// <param name="employeeID"></param>
/// <param name="department"></param>
/// <param name="title"></param>
/// <param name="company"></param>
public void ModifyUser(string employeeID, string department, string title, string company)
{
DirectoryEntry de = AdHerlp.GetDirectoryEntry();
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&(objectCategory=Person)(objectClass=user)(employeeID=" + employeeID + "))";
ds.SearchScope = SearchScope.Subtree;
SearchResult results = ds.FindOne(); if (results != null)
{
DirectoryEntry dey = AdHerlp.GetDirectoryEntry(results.Path);
SetProperty(dey, "department", department);
SetProperty(dey, "title", title);
SetProperty(dey, "company", company);
dey.CommitChanges();
dey.Close();
} de.Close();
} /// <summary>
/// 检验Email格式是否正确
/// </summary>
/// <param name="mail"></param>
/// <returns></returns>
public bool IsEmail(string mail)
{
Regex mailPattern = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
return mailPattern.IsMatch(mail);
} /// <summary>
/// 搜索被修改过的用户
/// </summary>
/// <param name="fromdate"></param>
/// <returns></returns>
public DataTable GetModifiedUsers(DateTime fromdate)
{
DataTable dt = new DataTable();
dt.Columns.Add("EmployeeID");
dt.Columns.Add("Name");
dt.Columns.Add("Email"); DirectoryEntry de = AdHerlp.GetDirectoryEntry();
DirectorySearcher ds = new DirectorySearcher(de); StringBuilder filter = new StringBuilder();
filter.Append("(&(objectCategory=Person)(objectClass=user)(whenChanged>=");
filter.Append(ToADDateString(fromdate));
filter.Append("))"); ds.Filter = filter.ToString();
ds.SearchScope = SearchScope.Subtree;
SearchResultCollection results = ds.FindAll(); foreach (SearchResult result in results)
{
DataRow dr = dt.NewRow();
DirectoryEntry dey = AdHerlp.GetDirectoryEntry(result.Path);
dr["EmployeeID"] = dey.Properties["employeeID"].Value;
dr["Name"] = dey.Properties["givenname"].Value;
dr["Email"] = dey.Properties["mail"].Value;
dt.Rows.Add(dr);
dey.Close();
} de.Close();
return dt;
} /// <summary>
/// 格式化AD的时间
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public string ToADDateString(DateTime date)
{
string year = date.Year.ToString();
int month = date.Month;
int day = date.Day; StringBuilder sb = new StringBuilder();
sb.Append(year);
if (month < )
{
sb.Append("");
}
sb.Append(month.ToString());
if (day < )
{
sb.Append("");
}
sb.Append(day.ToString());
sb.Append("000000.0Z");
return sb.ToString();
}
}
}
有了这个操作类,就可以进行域账号的创建了,调用示例:
Console.WriteLine("Begin CreateNewUser");
string name = "wj" + System.Guid.NewGuid().ToString().Substring(, );
string id = System.Guid.NewGuid().ToString().Substring(, );my.CreateNewUser(id, name, name, name + "@testhr.com", "testhr.com/Users");
Console.WriteLine("域用户名创建成功:" + name);
注意域账号的用户名不能有类似-,下划线之类的特殊字符。
在最初尝试的时候,创建对象 DirectoryEntry的时候总是有问题,最终这两种方式都是有效的:
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://testhr.com/CN=Users,DC=testhr,DC=com";
de.Username = @"administrator";
de.Password = "litb20!!";
return de;
DirectoryEntry entry = new
DirectoryEntry("LDAP://testhr.com", "administrator", "litb20!!",
AuthenticationTypes.Secure);
return entry;
其次,在创建完用户以后,需要设置用户的密码,这个方法总是报错,后来经过检查,发现如果只传递path字符串,是不行的,必须操作现有对象的Invoke方法才可以!
或者传递对象引用。
最终,成功创建了域账户。
在测试的时候,同一台机器加入了多个账号后,就会有问题,报出类似这样的错误:

最终,可以通过在服务器上删除这台电脑的方式来解决,或者重命名本地计算机名称。

当程序放在服务器上时,又报了错误:
Info:该服务器不可操作。
在 System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
在 System.DirectoryServices.DirectoryEntry.Bind()
在 System.DirectoryServices.DirectoryEntry.get_IsContainer()
在 System.DirectoryServices.DirectoryEntries.CheckIsContainer()
在 System.DirectoryServices.DirectoryEntries.Add(String name, String schemaClassName)
在 Litb.HRExtension.ADHelper.CreateNewUser(String name, String password, String firstname, String lastname, String email, String group)
位置 f:\code\HrExtension\Litb.HRExtension\Litb.HRExtension\ADHelper.cs:行号 87
在 ConsoleTest.Program.Main(String[] args) 位置 f:\code\HrExtension\Litb.HRExtension\ConsoleTest\Program.cs:行号 42
最终找到的原因是服务器win2003的DNS设为了一个固定ip,而这台机器没有对litb-inc.com的解析。
最终修改了DNS配置,问题解决。
C# LDAP 管理(创建新用户)的更多相关文章
- TestCase--网站创建新用户管理模块
对于web测试,用户权限管理模块是必测的一个点,所以今天就来总结一下创建新用户管理模块的测试用例 参考图如下: 测试用例设计如下: 一.功能测试 1. 什么都不输入,单击“立即提交”,页面是否有提示 ...
- mysql 权限分配及创建新用户
前言 本文主要是介绍mysql创建新用户命令及赋予权限等命令,为了便于理解,文中会给出相关示例.通常情况下,创建用户,修改mysql密码,授权,是需要有mysql里的root权限. 1.创建用户: / ...
- 给sftp创建新用户、默认打开和限制在某个目录
一.环境: CentOS 6.8 使用 FileZilla 进行 sftp 连接 二.背景 给外包的工作人员提供我司服务器的某一目录的访问(包括读写)权限,方便他们部署代码文件. 之所以是某一目录的访 ...
- centos7创建新用户
创建新用户 创建一个叫xiaoming的用户: [root@192 ~]# adduser xiaoming 为这个用户初始化密码,linux会判断密码复杂度,不过可以强行忽略: [root@192 ...
- Linux下如何创建新用户
Linux下如何创建新用户 Linux系统中,只有root用户有创建其他用户的权限.创建过程如下: useradd -d /home/newuser newuser(设定了该用户的主目录和用户名) ...
- linux创建新用户以及修改密码
1. 使用root账户创建新用户 useradd webuser 2. 修改新增的用户的密码 passwd webuser 这时候会提示你输入新的密码: 注意:不要用su webuser进入该账户修改 ...
- 创建新用户,连接Oracle数据库
1.sys用户是最高管理员用户,那我们就用这个sys用户登录oracle:
- Mysql创建新用户后无法登录,提示 Access denied for user 'username'@'localhost' (using password: YES)
MySQL创建新用户后无法登录,提示 Access denied for user 'username'@'localhost' (using password: YES) ,多半是因为存在匿名用户, ...
- oracle用sqlplus创建新用户,不是plsql developer
1.sqlplus /nolog 2.conn /as sysdba 3.alter user system identified by "123456"; 4.alter use ...
- linux useradd(adduser)命令参数及用法详解(linux创建新用户命令)
linux useradd(adduser)命令参数及用法详解(linux创建新用户命令) useradd可用来建立用户帐号.帐号建好之后,再用passwd设定帐号的密码.而可用userdel删除帐号 ...
随机推荐
- PM俱乐部之旅7-弱活着
有些人认为,最终我们放松一点时间,有意想不到的事情发生--公司组织结构调整. 公司由于业务范围调整,所以要进行对应的组织结构调整.PMO部门也随之重组,项目经理俱乐部的活动改成项目交流会,请项目 ...
- Oracle Hints详细解释
特别介绍给大家Oracle Hints之前,让我们知道下Oracle Hints什么,然后好Oracle Hints,我们希望实际.基于成本的优化器是很聪明,在大多数情况下,将选择正确的优化,减少DB ...
- Java Web整合开发(78) -- Struts 1
在Struts1.3中已经取消了<data-sources>标签,也就是说只能在1.2版中配置,因为Apache不推荐在 struts-config.xml中配置数据源.所以建议不要在st ...
- Cocos2d-x示例:单点触摸事件
为了让大家掌握Cocos2d-x中的事件机制,以下我们以触摸事件为例.使用事件触发器实现单点触摸事件.该实比如图8-3所看到的,场景中有三个方块精灵,显示顺序如图8-3所看到的,拖拽它们能够移动它们. ...
- Linux下一个OTL 采用long long类型数据库支持BIGINT
码如下面: #define OTL_BIGINT long long #define OTL_STR_TO_BIGINT(str,n) \ { \ n=atoll(str); \ } #define ...
- 【Unity技能】做一个简单的NPC
1. 写在前面 前几天我看到cgcookie一个教程.学习了下怎么依据已有人物模型制作一个仿版的NPC人物.感觉挺好玩的,整理一下放到博客里! 先看一下教程里面的终于效果. 是不是非常像个幽灵~ 以下 ...
- 【Web探索之旅】第一部分:什么是Web?
内容简介 1.Web探索之旅:开宗明义 2.第一部分第一课:什么是Web? 3.第一部分第二课:Web,服务和云 4.第一部分第三课:Web的诞生史 Web探索之旅:开宗明义 大家好. 我们这个系列课 ...
- java提高篇(十一)-----代码块
在编程过程中我们可能会遇到如下这种形式的程序: public class Test { { //// } } 这种形式的程序段我们将其称之为代码块,所谓代码块就是用大括号({})将多行代码封装在一起, ...
- 各种ESB产品比较(转)
介绍了主流商业和开源ESB的发展趋势.可借鉴的地方和其缺点: 主要介绍: Oracle Service Bus WebSphere Message Broker ...
- iPhone&iPad DFU及恢复模式刷机、降级教程
再次提醒,刷机需慎重处理. http://blog.csdn.net/ztp800201/article/details/11980643 iphone一共同拥有三种工作模式,各自是正常模式,恢复模式 ...