C# 操作LDAP
C# 操作LDAP查找组或人员信息
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.DirectoryServices; /// <summary>
///ADUtil 的摘要说明
/// </summary>
public class ADUtil
{
// LDAP地址 例如:LDAP://my.com.cn
private const string LDAP_HOST = "LDAP://my.com.cn";
// 具有LDAP管理权限的特殊帐号
private const string USER_NAME = "account";
// 具有LDAP管理权限的特殊帐号的密码
private const string PASSWORD = "password"; public ADUtil()
{
//
//TODO: 在此处添加构造函数逻辑
//
} /**
* 向某个组添加人员
* groupName 组名称
* userName 人员域帐号
**/
public static void addGroupMember(string groupName, string userName)
{
DirectoryEntry group = getGroupByName(groupName);
group.Username = USER_NAME;
group.Password = PASSWORD;
group.Properties["member"].Add(getUserDNByName(userName));
group.CommitChanges();
} /**
* 从某个组移出指定的人员
* groupName 组名称
* userName 人员域帐号
**/
public static void removeGroupMember(string groupName, string userName)
{
DirectoryEntry group = getGroupByName(groupName);
group.Username = USER_NAME;
group.Password = PASSWORD;
group.Properties["member"].Remove(getUserDNByName(userName));
group.CommitChanges();
} /**
* 获取指定人员的域信息
* name 人员域帐号
**/
public static object getUserDNByName(string name)
{
DirectorySearcher userSearch = new DirectorySearcher(LDAP_HOST);
userSearch.SearchRoot = new DirectoryEntry(LDAP_HOST, USER_NAME, PASSWORD);
userSearch.Filter = "(SAMAccountName=" + name + ")";
SearchResult user = userSearch.FindOne();
if (user == null)
{
throw new Exception("请确认域用户是否正确");
}
return user.Properties["distinguishedname"][];
} /**
* 获取指定域组的信息
* name 组名称
**/
public static DirectoryEntry getGroupByName(string name)
{
DirectorySearcher search = new DirectorySearcher(LDAP_HOST);
search.SearchRoot = new DirectoryEntry(LDAP_HOST, USER_NAME, PASSWORD);
search.Filter = "(&(cn=" + name + ")(objectClass=group))";
search.PropertiesToLoad.Add("objectClass");
SearchResult result = search.FindOne();
DirectoryEntry group;
if (result != null)
{
group = result.GetDirectoryEntry();
}
else {
throw new Exception("请确认AD组列表是否正确");
}
return group;
}
}
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
{
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; //DirectoryEntry entry = new DirectoryEntry("LDAP://testhr.com", "administrator", "litb20!!", AuthenticationTypes.Secure);
//return entry; }
#endregion #region 获取目录实体集合
/// <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操作类 //myDirectory.cs public class myDirectory
{ /// <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="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()
{
//RandomPassword rp = new RandomPassword();
return "qwe123!@#";
} /// <summary>
/// 设置用户新密码
/// </summary>
/// <param name="path"></param>
public void SetPassword(DirectoryEntry newuser)
{
//DirectoryEntry usr = new DirectoryEntry();
//usr.Path = path;
//usr.AuthenticationType = AuthenticationTypes.Secure; //object[] password = new object[] { SetSecurePassword() };
//object ret = usr.Invoke("SetPassword", password);
//usr.CommitChanges();
//usr.Close(); 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>
/// <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)
{
//Catalog catalog = new Catalog();
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();
//newuser.Close(); //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="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方法才可以!
或者传递对象引用。
最终,成功创建了域账户。
在测试的时候,同一台机器加入了多个账号后,就会有问题,报出类似这样的错误:
最终,可以通过在服务器上删除这台电脑的方式来解决,或者重命名本地计算机名称。
C#LDAP删除用户
一、创建LDAP连接
二、准备用户拥有的属性
三、 删除用户的信息
LdapConnection conn = new LdapConnection();
conn.Connect("192.168.3.112", );
string dn = "CN=Administrator,CN=Users,DC=baiyi,DC=com";
conn.Bind(dn, "etimes2011@");
sbyte[] mysbyte = new sbyte[caByte.Length];
for (int i = ; i < caByte.Length; i++)
{
if (caByte[i] > )
{
mysbyte[i] = (sbyte)(caByte[i] - );
}
else
{
mysbyte[i] = (sbyte)(caByte[i]);
}
}
LdapAttribute attribute = new LdapAttribute("userCertificate", mysbyte);
string user = "CN=foodean,CN=Users,DC=baiyi,DC=com";
conn.Modify(user, new LdapModification(LdapModification.DELETE, attribute));//注意这里使用的是DELETE
conn.Disconnect();
C# 操作LDAP的更多相关文章
- JAVA操作LDAP的详解(JLDAP)
最近两周由于要学习测试LDAP,所以对于用脚本操作LDAP很感兴趣,所以就做了一些脚本,都是比较简单的脚本吧. 废话不多说了哈.直接上教程 首先声明:我使用的是JLDAP操作LDAP,所以需要从官网下 ...
- springLdap 操作ldap示例(增删改查)
转自:http://blog.csdn.net/sundenskyqq/article/details/9002440 这部分的示例网上的确有很多,但是个人在查找的过程中还是感到不够满意,所以就自己总 ...
- 配置OpenLDAP,Java操作LDAP,DBC-LDAP进访问
LDAP快速入门 1. LDAP简介 LDAP(轻量级目录访问协议,Lightweight Directory Access Protocol)是实现提供被称为目录服务的信息服务.目录服务是一种特殊的 ...
- JAVA操作LDAP总结
一.LDAP概念 LDAP的全称为Lightweight Directory Access Protocol(轻量级目录访问协议), 基于X.500标准, 支持 TCP/IP. LDAP目录为数据库, ...
- 使用JLDAP操作LDAP,包含匿名连接、ldif导入导出、获取根节点、对数据的操作、LDAP错误码解析等
bean类 package com.cn.ccc.ggg.ldap.model; import javax.persistence.Entity; import javax.persistence.T ...
- #JAVA操作LDAP
package com.wisdombud.unicom.monitor.ldap; import java.util.ArrayList; import org.slf4j.Logger; impo ...
- [原创]django+ldap+memcache实现单点登录+统一认证
前言 由于公司内部的系统越来越多,为了方便用户使用,通过django进行了单点登录和统一认证的尝试,目前实现了django项目的单点登录和非django项目的统一认证,中间波折挺多,涉及的技术包括dj ...
- [原创]django+ldap实现单点登录(装饰器和缓存)
前言 参考本系列之前的文章,我们已经搭建了ldap并且可以通过django来操作ldap了,剩下的就是下游系统的接入了,现在的应用场景,我是分了2个层次,第一层次是统一认证,保证各个系统通过ldap来 ...
- [原创]django+ldap实现统一认证部分一(django-auth-ldap实践)
前言 接之前我的文章,django+ldap+memcache实现单点登录+统一认证 ,ldap部署相关,ldap双机\LAM配置管理\ldap备份还原,目前来说,我们已经有了高可用性的ldap环境了 ...
随机推荐
- Android实用的Toast工具类封装
Toast这个提示框大家都晓得,显示一段时间后自动消失,不能获得焦点.但是在使用中有些问题: 1)需要弹出一个新的Toast时,上一个Toast还没有显示完2)可能重复弹出相同的信息3)Toast具体 ...
- pycharm 使用Git提交代码到Github
pycharm 使用Git提交代码到Github pytharm 创建django项目,提交到github总是失败,在github创建项目拉下来后项目层级会多一层,为此查了一些资料,亲测如下方式可行. ...
- linux重要的配置文件列表
启动引导程序配置文件 LILO /etc/lilo.conf GRUB /boot/grub/menu.lst 系统启动文件核脚本 主启动控制文件 /etc/inittab SysV启动脚本的位置 / ...
- mysql dump备份 、 mysql还原操作练习
1.备份mysql.dump 备份MySQL数据库的命令 mysqldump -h主机名 -u用户名 -p密码 数据库名字 > 备份的数据库名字.sql 例子: mysqldump -uroot ...
- qos-server can not bind localhost:22222, dubbo version: 2.6.0, current host: 127.0.0.1【问题解决】
好吧,这个问题比较low,但是记录一下,以免后期遗忘. 说白了,这个问题就是端口被占用了. 问题: qos-server can not bind localhost:22222, dubbo ver ...
- 在linux下配置jupyter notebook,本地浏览器访问
1.安装jupyter notebook pip install jupyter 2.生成配置文件 jupyter notebook --generate-config 3.设置登陆密码并生成秘钥 s ...
- 201871020225-牟星源《面向对象程序设计(java)》第十三周学习总结
201871020225-牟星源<面向对象程序设计(java)>第十三周学习总结 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ ...
- python的requests库
requests是在爬虫中常用到的一个库,它可以帮助我们很好的去请求我们想要爬取的网站,并返回网站的内容. 0x01:请求 get请求.post请求这两个是最常用的请求方式,此外还有类似delete. ...
- MyBatisPlus快速入门
MyBatisPlus快速入门 官方网站 https://mp.baomidou.com/guide 慕课网视频 https://www.imooc.com/learn/1130 入门 https:/ ...
- Provider和Consumer的搭建(六)
创建三个Maven Project: dubbo-service:公共模块,包括服务接口(packaging:jar) dubbo-service-impl:服务提供方,提供服务接口的具体实现,需要依 ...