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. m2eclipse安装遇到的问题——备忘

    手贱把m2eclipse给卸载了,结果重新安装的时候,发现原来的网址不好用了,去官网查了发现改成了http://download.eclipse.org/technology/m2e/releases ...

  2. WCF中操作的分界于调用顺序和会话的释放

    操作分界 在WCF操作契约的设计中,有时会有一些调用顺序的业务,有的操作不能最先调用,有的操作必须最后调用,比如在从一个箱子里拿出一件东西的时候,必须先要执行打开箱子的操作,而关上箱子的操作应该在一切 ...

  3. VR电竞游戏在英特尔®架构上的用户体验优化

    作为人与虚拟世界之间的新型交互方式,VR 能够让用户在模拟现实中获得身临其境的感受.但是,鉴于 VR 的帧预算为每帧 11.1ms (90fps),实现实时渲染并不容易,需要对整个场景渲染两次(一只眼 ...

  4. Hyperledger Fabric 1.1 -- Policy 构成

    Policy 规则设计 本文主要是讲解一下在fabric中Policy的规则和写法,让大家有一个初步的认识,本文是基于fabric 1.1版本 Policy Type Policy Type 目前包括 ...

  5. XSS 注入检查点

    如果你有个论坛,一般你会很注意用户发帖的注入问题,往往这个地方不会被注入,因为开发特别照顾.原则上XSS都是用户输入的,但是许多边角还是容易忽略.枚举一些检查点. 分页 分页通用组件获取url,修改p ...

  6. jupyter通过notedown使用markdown

    0 Problem 最近看了下李沐老师的mxnet教程,在使用jupyter的时候打开教程发现全是markdown源文,没有展示markdown格式的文字. 1 Reason 源代码是用markdow ...

  7. 如何让QT程序以管理员权限运行(UAC)

    方案一:(仅适用于使用msvc编译器) 在PRO文件中添加一行指令即可, QMAKE_LFLAGS += /MANIFESTUAC:"level='requireAdministrator' ...

  8. c# 加载图片 正在被占用问题

    问题情境:图片文件加载到pdf中,程序没有退出,再次加载该图片文件,提示被占用. 解决办法: 1.加载文件会锁定该文件,fromfile方法会导致占用内存较大,不使用该方法. FileStream f ...

  9. OOP 1.4 内联函数和重载函数函数参数缺省值

    1.内联函数 存在的背景:函数调用存在开销(调用时候参数压栈,返回地址压栈:返回时从栈取出返回地址,跳转到返回地址.总共需要几条指令的开销).如果函数指令较少,调用多次,函数调用的开销占比大. 内联函 ...

  10. struts2 不返回result的做法

    有时候 比如提交一个弹框的表单 提交成功后我们只是让表单关闭并不进行页面跳转,那么action 里面就returne null, 然后result 也不用配置了 版权声明:本文为博主原创文章,未经博主 ...