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. Shell if 判断语句参数

    [ -a FILE ] 如果 FILE 存在则为真. [ -b FILE ] 如果 FILE 存在且是一个块特殊文件则为真. [ -c FILE ] 如果 FILE 存在且是一个字特殊文件则为真. [ ...

  2. 【redis的链接】redis的两种连接方法

    执行redis-server /etc/redis.conf开启服务 方法一: [root@zhangmeng ~]# redis-cli > > quit 方法二: [root@zhan ...

  3. 在docker中执行linux shell命令

    在docker中执行shell命令,需要在命令前增加sh -c,例如: docker run ubuntu sh -c 'cat /data/a.txt > b.txt' 否则,指令无法被正常解 ...

  4. Pandas v0.23.4手册汉化

    Pandas手册汉化 此页面概述了所有公共pandas对象,函数和方法.pandas.*命名空间中公开的所有类和函数都是公共的. 一些子包是公共的,其中包括pandas.errors, pandas. ...

  5. loadrunner之做压力测试要做的准备

    前提B/S架构 1.要有个备库和主库保存一致 到时候做压力测试的时候,要断开主库连接到备库.进行测试.以免主库出现垃圾数据.2.节点 判断单节点能承受多大的压力,如200万的用户账号,10万的在线用户 ...

  6. C#与mongoDB初始环境搭建

    mongoDB官网https://www.mongodb.com/ mongoDB默认安装路径(Windows x64平台) C:\Program Files\MongoDB\Server\3.4\b ...

  7. Java普通编程和Web网络编程准备工作

    一.工具下载 链接:https://pan.baidu.com/s/1geOdq3h 密码:pzl5 二.Java普通编程 解压下载的资料,并按readme.txt安装jdk和Eclipse. 三.J ...

  8. TPO 02 - Early Cinema

    TPO 02 - Early Cinema NOTE: 主要意思(大概就是主谓宾)用粗体标出:重要的其它用斜体: []中的是大致意思,可能与原文有关也可能无关,但不会离题 目的为训练句子/段落总结能力 ...

  9. 【转】PHPCMS+PHPExcel实现后台数据导入导出功能

    首先,上图之中的红色框框是没有的,我们想要给他加上,当然是要改HTML页面啦,废话,我们跟ECSHOP一样由PHP路径找模板: 看看路由原理: 首先,上图之中的红色框框是没有的,我们想要给他加上,当然 ...

  10. 利用xlsxwriter生成数据报表

    #!/usr/bin/env python# -*- coding:utf-8 -*-import os,xlsxwriter,datetimeimport ConfigParserfrom send ...