1、获取windows AD域用户信息,首先需要有一个ad域管理员权限的账号,用这个账号连接ad域,获取所有域用户信息

用LdapContext,它继承自DirContext

public Object getAllAdUserNames() {
List<String> list = new ArrayList<>();
String username = "lisi@ad.com";
String password = "123@abc.com"; String url = "ldap://192.168.44.40:389"; //使用ldap协议连接windows ad域,缺省端口是389
Hashtable env = new Hashtable(); env.put(Context.SECURITY_AUTHENTICATION, "simple");//"none","simple","strong"
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password);
NamingEnumeration results = null;
try {
LdapContext ctx = new InitialLdapContext(env,null);
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = "(&(objectCategory=person)(objectClass=user)(name=*))";
String searchBase = "DC=ad,DC=com";
// String returnedAtts[] = {"memberOf"}; //获取登录名,samaccountname是兼容windows2000以前系统的(如:lisi),userprincipalname是带域名的登录名(如:lisi@ad.com)
       String returnedAtts[] = {"samaccountname", "userprincipalname"};
searchControls.setReturningAttributes(returnedAtts); NamingEnumeration<SearchResult> result = ctx.search(searchBase,searchFilter,searchControls);
while (result.hasMoreElements()) {
SearchResult searchResult = (SearchResult) result.next();
list.add(searchResult.getName());
System.out.println("[" + searchResult.getName() + "]");
}
ctx.close();
} catch (AuthenticationException e) {
e.printStackTrace();
return e.toString();
} catch (NameNotFoundException e) {
e.printStackTrace();
return e.toString();
} catch (NamingException e) {
e.printStackTrace();
return e.toString();
} finally {
if (results != null) {
try {
results.close();
} catch (Exception e) {
}
}
}
return list;
}

2、用DirContext,与上边略有区别

  public List<String> getAllPersonNames() {
String username = "lisi@ad.com";
String password = "123@abc.com"; Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://192.168.44.40:389/dc=ad,dc=com");
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password); DirContext ctx;
try {
ctx = new InitialDirContext(env);
} catch (NamingException e) {
throw new RuntimeException(e);
} List<String> list = new ArrayList<>();
NamingEnumeration<SearchResult> results = null;
try {
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "(&(objectCategory=person)(objectClass=user)(name=*))";
results = ctx.search("", searchFilter, controls); while (results.hasMoreElements()) {
SearchResult searchResult = results.next();
Attributes attributes = searchResult.getAttributes();
Attribute attr = attributes.get("cn");
String cn = attr.get().toString();
list.add(cn);
}
} catch (NameNotFoundException e) {
e.printStackTrace();
} catch (NamingException e) {
e.printStackTrace();
} finally {
if (results != null) {
try {
results.close();
} catch (Exception e) {
// Never mind this.
}
}
if (ctx != null) {
try {
ctx.close();
} catch (Exception e) {
// Never mind this.
}
}
}
return list;
}

3、用Spring集成ldap

依赖

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>

application.yml的配置,一种方式自定义ldap,一种是直接采用spring data集成

3.1自定义,重载LdapTemplate

application.yml

#自定义的ldap config
ldap:
base: OU=开发部,DC=ad,DC=com
url: "ldap://192.168.44.40:389"
username: xu.dm@ad.com
password: "123@abc.com"
referral: follow
LdapConfig,referral参数具体含义不明确,可以注销了
@Configuration
public class LdapConfig { @Value("${ldap.url}")
private String ldapUrl; @Value("${ldap.base}")
private String ldapBase; @Value("${ldap.username}")
private String ldapUserDn; @Value("${ldap.password}")
private String ldapUserPwd; @Value("${ldap.referral}")
private String ldapReferral; @Bean
public LdapTemplate ldapTemplate() {
return new LdapTemplate(contextSourceTarget());
} @Bean
public LdapContextSource contextSourceTarget() {
LdapContextSource ldapContextSource = new LdapContextSource(); ldapContextSource.setUrl(ldapUrl);
ldapContextSource.setBase(ldapBase);
ldapContextSource.setUserDn(ldapUserDn);
ldapContextSource.setPassword(ldapUserPwd);
// ldapContextSource.setReferral(ldapReferral);
ldapContextSource.setPooled(false);
ldapContextSource.afterPropertiesSet();
return ldapContextSource;
}
}
@Service
public class LdapServiceImpl implements LdapService { @Resource
LdapTemplate ldapTemplate; @Override
public Iterable<User> getUserList(String cn) {
LdapQuery query = LdapQueryBuilder.query().attributes("cn").where("objectclass")
.is("user").and("cn").is(cn);
return ldapTemplate.find(query,User.class);
} @Override
public User create(User user) {
ldapTemplate.create(user);
return user;
} @Override
public void delete(User user) {
ldapTemplate.delete(user);
} } @Override
public Iterable<User> findAll() {
return ldapTemplate.findAll(User.class);
}
}

实体:

@Entry(base = "dc=ad,dc=com", objectClasses = {"top","person"})
public class User implements Serializable { @Id
@JsonIgnore
private Name dn; // @DnAttribute(value = "distiguishedName")
// private String distinguishedName; @Attribute(name = "cn")
// @DnAttribute(value="cn", index=1)
private String commonName; @Attribute(name = "sn")
private String suerName; @Attribute(name="userPassword")
private String userPassword; // @DnAttribute(value="ou", index=0)
@Attribute(name="ou")
private String organizaitonUnit; @Attribute(name="displayName")
private String displayName; public User() {
} public User(String commonName, String organizaitonUnit) {
Name dn = LdapNameBuilder.newInstance()
.add("ou",organizaitonUnit)
.add("cn",commonName)
.build();
this.dn = dn;
this.commonName = commonName;
this.organizaitonUnit = organizaitonUnit;
} 。。。 。。。略
}

3.2 Spring data集成方式

application.yml

#spring data方式
spring:
ldap:
base: OU=开发部,DC=ad,DC=com
urls: "ldap://192.168.44.40:389"
username: xu.dm@ad.com
password: "123@abc.com"
public interface UserRepository extends LdapRepository<User> {
}
@Service
public class LdapServiceImpl implements LdapService { @Resource
UserRepository userRepository; @Override
public User findOne(String cn) {
LdapQuery query = LdapQueryBuilder.query().attributes("cn").where("objectclass")
.is("person").and("cn").is(cn);
return userRepository.findOne(query).orElse(null);
} }

获取和验证Windows AD域的用户信息的更多相关文章

  1. Windows AD域升级方

    前面的博客中我谈到了网络的基本概念和网络参考模型,今天我们来谈企业中常用的技术,Windows AD 域,今天我的笔记将重点讲解Windows AD 域的升级和迁移方法,通过3个小实验进行配置,真实环 ...

  2. Windows AD域管理软件是什么?

    Windows AD域管理软件是什么? ADManager Plus是一个简单易用的Windows AD域管理工具,帮助域管理员简化日常的管理工作.通过直观友好的操作界面,可以执行复杂的管理操作,比如 ...

  3. jsonp跨域实现单点登录,跨域传递用户信息以及保存cookie注意事项

    网站A:代码:网站a的login.html页面刷新,使用jsonp方式将信息传递给b.com的login.php中去,只需要在b.com中设置一下跨域以及接收参数,然后存到cookei即可, 注意:网 ...

  4. asp.net用户身份验证时读不到用户信息的问题 您的登录尝试不成功。请重试。 Login控件

    原文:asp.net用户身份验证时读不到用户信息的问题 您的登录尝试不成功.请重试. Login控件 现象1.asp.net使用自定义sql server身份验证数据库,在A机器新增用户A,可以登录成 ...

  5. ASP.NET站点Windows身份验证集成AD域,非LDAP

    站点集成AD域验证 服务器机器入域 计算机右键属性-->“更改设置”-->“更改”-->填写所属域,确认后重启机器生效. 部署测试站点,localhost.ip.域名三种方式登录效果 ...

  6. windows AD域安装及必要设置

    一.安装AD域 运行dcpromo命令,安装AD域. 步骤: 1.win+R 2.dcpromo 图例: 百度百科关于“dcpromo”解释: dcpromo命令是一个“开关”命令.如果Windows ...

  7. AD域 根据 用户属性userAccountControl 来判断用户禁用属性

    参考:https://support.microsoft.com/zh-cn/help/305144/how-to-use-the-useraccountcontrol-flags-to-manipu ...

  8. 将AD域漫游用户配置文件放在samba服务器中

    书接上回https://www.cnblogs.com/jackadam/p/11448497.html 我们已经将linux服务器设置为域成员,启动samba服务后,已经实现了使用域账号验证,自动创 ...

  9. AD域创建用户无法登录

    怎么登录都无法登录 解决办法: 创建用户的时候   将用户下次登录时须更改密码的勾去掉    不然需要修改密码才可以登录

随机推荐

  1. .net mvc 使用ueditor的开发(官网没有net版本?)

    1.ueditor的下载导入 官网下载地址:https://ueditor.baidu.com/website/download.html · 介绍 有两种,一种开发版,一种Mini版,分别长这样: ...

  2. Qt-QML-电子罗盘

    使用QML中的Canvas实现电子罗盘绘制,效果图如下 一个简单的电子罗盘,红色N极.其中中间飞机表示当前的指向, 还是比较简单的,直接上代码吧 /* 作者:张建伟 时间:2018年4月27日 简述: ...

  3. ESP8266 NON-OS SDK 和 RTOS SDK实现GPIO中断不同点

    ESP8266 Non-OS SDK 和 RTOS SDK 实现GPIO的方法稍有不同: 对于 Non-OS SDK,比如需要把 MTDO 配置成输入,同时下降沿触发中断: gpio_init(voi ...

  4. Appium+python 自动发送邮件(2)(转)

    (原文:https://www.cnblogs.com/fancy0158/p/10056418.html) 移动端执行完测试case之后,通过邮件自动发送测试报告.大体流程如下: 1.通过unitt ...

  5. 使用Photon引擎进行unity网络游戏开发(四)——Photon引擎实现网络游戏逻辑

    使用Photon引擎进行unity网络游戏开发(四)--Photon引擎实现网络游戏逻辑 Photon PUN Unity 网络游戏开发 网络游戏逻辑处理与MasterClient 网络游戏逻辑处理: ...

  6. Mybatis利用拦截器做统一分页

    mybatis利用拦截器做统一分页 查询传递Page参数,或者传递继承Page的对象参数.拦截器查询记录之后,通过改造查询sql获取总记录数.赋值Page对象,返回. 示例项目:https://git ...

  7. 简单主机批量管理工具(这里实现了paramiko 用su切换到root用户)

    项目名:简单主机批量管理工具 一.需求 1.主机分组 2.可批量执行命令.发送文件,结果实时返回,执行格式如下 batch_run  -h h1,h2,h3   -g web_clusters,db_ ...

  8. [shell] awk学习

    awk处理最后一行 awk '{if(NR>1)print a;a=$0}END{print a="b"}' file awk 'BEGIN{getline a}{print ...

  9. 20181016-4 Alpha阶段第1周/共2周 Scrum立会报告+燃尽图 02

    此次作业要求参见 [https://edu.cnblogs.com/campus/nenu/2018fall/homework/2247] Scrum master:祁玉 一.小组介绍 组长:王一可 ...

  10. Dijkstra 最短路径算法 秒懂详解

    想必大家一定会Floyd了吧,Floyd只要暴力的三个for就可以出来,代码好背,也好理解,但缺点就是时间复杂度高是O(n³). 于是今天就给大家带来一种时间复杂度是O(n²),的算法:Dijkstr ...