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. 深度学习:参数(parameters)和超参数(hyperparameters)

    1. 参数(parameters)/模型参数 由模型通过学习得到的变量,比如权重和偏置 2. 超参数(hyperparameters)/算法参数 根据经验进行设定,影响到权重和偏置的大小,比如迭代次数 ...

  2. 微服务介绍及Asp.net Core实战项目系列之微服务介绍

    0.目录 整体架构目录:ASP.NET Core分布式项目实战-目录 一.微服务选型 在做微服务架构的技术选型的时候,我们以“无侵入”和“社区活跃”为主要的考量点,将来升级为原子服务架构.量子服务架构 ...

  3. dubbo常见的一些面试题

    什么是Dubbo? Duubbo是一个RPC远程调用框架, 分布式服务治理框架 什么是Dubbo服务治理? 服务与服务之间会有很多个Url.依赖关系.负载均衡.容错.自动注册服务. Dubbo有哪些协 ...

  4. 003 -- Dubbo简单介绍

    1:Dubbo的基本概念 dubbo是阿里巴巴SOA服务治理 方案的核心框架,每天为20000+个服务次的数据量访问支持.dubbo是一个分布式的服务框架,致力于提供高性能和透明化的RPC远程服务调用 ...

  5. 3.5星|《算法霸权》:AI、算法、大数据在美国的阴暗面

    算法霸权 作者在华尔街对冲基金德绍集团担任过金融工程师,后来去银行做过风险分析,再后来去做旅游网站的用户分析.后来辞职专门揭露美国社会生活背后的各种算法的阴暗面. 书中提到的算法的技术缺陷,我归纳为两 ...

  6. LVM缩小根分区

    逻辑卷不是根分区都可以在线扩容和缩小 根分区是可以在线扩容,但不可以在线缩小 Linux系统进入救援模式 依次选择: 欢迎界面 ---------- Rescue installed system C ...

  7. ArcFace Demo [Android]

    Free SDK demo 工程如何使用? 1.下载代码:git clone https://github.com/asdfqwrasdf/ArcFaceDemo.git 或者直接下载压缩包 2.前往 ...

  8. ES6中Class的继承关系

    es5实现中,每个对象都有__proto__属性(也就是关系图中[[prototype]]属性),指向对应的构造函数的prototype.Class 作为构造函数的语法糖,同时有prototype属性 ...

  9. 《C》数组

    数组 数组方法: var arr = [1, 2, 3]; arr.push(4)://arr='[1, 2, 3, 4]' 向末尾添加一个或者多个元素 arr.pop()://删除末位元素 var ...

  10. 配置EditPlus编辑器使其成为Python的编辑、执行环境

    1.添加Python群组 运行EditPlus,选择工具→配置用户工具进入参数设置框. 单击添加工具→应用程序.菜单文字输入python,命令为Python的安装路径,参数输入 $(FileName) ...