Spring Boot 2.0 项目实现自同步AD域账号 顶

在通过Spring Boot的自动化装配功能及JDK自带的LDAP模块,可通过如下几个简单步骤实现业务系统自动同步AD域账号功能。

1. Java自带ldap搜索域账号信息核心代码:

try {
    LdapContext ctx = new InitialLdapContext(env, null);
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setReturningAttributes(new String[]{"name","sn","distinguishedName"});
    NamingEnumeration<SearchResult> answer = ctx.search("searchBase", "searchFilter", searchCtls);
    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();
        System.out.println("<<<::[" + sr.getName()+"]::>>>>");
    }
    ctx.close();
} catch (NamingException e) {
    e.printStackTrace();
}

2. 通过application.properties增加自定义配置

quickdoc.ldap.username=michael@mxleader.cn
quickdoc.ldap.password=chenbichao
quickdoc.ldap.url=LDAP://192.168.15.100:389
quickdoc.ldap.searchBase=OU=XXX有限公司,OU=XXX集团,DC=mxleader,DC=cn

3. 增加resources/META-INFO/spring.factories文件,内容如下:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=cn.mxleader.quickdoc.config.LDAPConfiguration

4. 增加属性Bean文件类LDAPProerties和LDAPConfiguration类, initLdapUsers方法通过Reactor方式实现业务系统启动时自动同步AD域账号的逻辑,不会阻塞业务进程。

@SpringBootConfiguration
@ConditionalOnClass(StreamService.class)
@EnableConfigurationProperties(LDAPProperties.class)
public class LDAPConfiguration {

    private final LDAPProperties ldapProperties;

    public LDAPConfiguration(LDAPProperties ldapProperties) {
        this.ldapProperties = ldapProperties;
    }

    @Bean
    public LDAPService ldapService(ConfigService configService) {
        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");//"none","simple","strong"
        env.put(Context.SECURITY_PRINCIPAL, ldapProperties.getUsername());
        env.put(Context.SECURITY_CREDENTIALS, ldapProperties.getPassword());
        env.put(Context.PROVIDER_URL, ldapProperties.getUrl());
        return new LDAPServiceImpl(configService, env, ldapProperties.getSearchBase(), ldapProperties.getBlacklist());
    }

    /**
     * 初始化LDAP域账号()
     *
     * @param ldapService
     * @param userService
     * @return
     */
    @Bean
    public CommandLineRunner initLdapUsers(LDAPService ldapService,
                                           UserService userService,
                                           DiskService diskService) {
        return args -> ldapService.searchLdapUsers()
                .filter(sysUser -> userService.get(sysUser.getUsername()) == null)
                .map(userService::saveUser)
                .subscribe(sysUser -> diskService.save("我的磁盘",
                        new Authorization(sysUser.getUsername(), AuthType.PRIVATE,
                                new HashSet<AuthAction>() {{
                                    add(AuthAction.READ);
                                    add(AuthAction.WRITE);
                                    add(AuthAction.DELETE);
                                }})));
    }

}

5. 增加LDAP操作服务接口和实现类

public interface LDAPService {

    Flux<SearchResult> searchLdapItems(String searchFilter, String returnedAtts[], String searchBase)
            throws NamingException;

    Flux<SysUser> searchLdapUsers(String searchBase) throws NamingException;

    Flux<SysUser> searchLdapUsers() throws NamingException;

    Flux<SearchResult> searchLdapGroups(String searchBase) throws NamingException;

    Flux<SearchResult> searchLdapGroups() throws NamingException;
}
public class LDAPServiceImpl implements LDAPService {

    private final Properties env;
    private final String defaultSearchBase;
    private final String blacklist[];
    private static final String defaultGroupFilter = "(&(objectCategory=Group)(objectClass=group)(name=*))";
    private static final String defaultPersonFilter = "(&(objectCategory=Person)(objectClass=user)(name=*))";
    private static final String defaultGroupAtts[] = {"distinguishedName", "name"};
    private static final String defaultPersonAtts[] = {"distinguishedName", "memberOf", "name", "sAMAccountName",
            "displayName", "title", "mail", "department"};

    private final ConfigService configService;

    public LDAPServiceImpl(ConfigService configService, Properties env, String defaultSearchBase,String blacklist[]) {
        this.configService = configService;
        this.env = env;
        this.defaultSearchBase = defaultSearchBase;
        this.blacklist = blacklist;
    }

    public Flux<SearchResult> searchLdapItems(String searchFilter, String returnedAtts[], String searchBase)
            throws NamingException {
        LdapContext ctx = new InitialLdapContext(env, null);
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchCtls.setReturningAttributes(returnedAtts);
        NamingEnumeration<SearchResult> answer = ctx.search(searchBase, searchFilter, searchCtls);
        Flux<SearchResult> searchResultFlux = Flux.fromStream(Collections.list(answer).stream());
        ctx.close();
        return searchResultFlux;
    }

    public Flux<SysUser> searchLdapUsers(String searchBase) throws NamingException {
        Flux<SysUser> sysUserFlux = searchLdapItems(defaultPersonFilter, defaultPersonAtts, searchBase)
                .map(sr -> {
                    try {
                        String sn = sr.getAttributes().get("sAMAccountName").get().toString();
                        String displayName = sr.getAttributes().get("displayName").get().toString();
                        String title = sr.getAttributes().get("title").get().toString();
                        String email = sr.getAttributes().get("mail").get().toString();
                        String department = sr.getAttributes().get("department").get().toString();
                        return new SysUser(ObjectId.get(), sn, displayName, title,
                                HanyuPinyinUtil.toHanyuPinyin(displayName),
                                configService.getSysProfile().getIconMap().get("AWARD"),
                                true, department,
                                new HashSet<SysUser.Authority>() {{
                                    add(SysUser.Authority.USER);
                                }},
                                new HashSet<String>() {{
                                    add(department);
                                }},
                                email);
                    } catch (NamingException exp) {
                        exp.printStackTrace();
                        return null;
                    }
                });
        // 过滤黑名单部门人员
        if(blacklist!=null && blacklist.length>0){
            return sysUserFlux.filter(sysUser -> {
                for (String blackItem : blacklist) {
                    if(sysUser.getDepartment().startsWith(blackItem))
                        return false;
                }
                return true;
            });
        }else {
            return sysUserFlux;
        }
    }

    public Flux<SysUser> searchLdapUsers() throws NamingException {
        return searchLdapUsers(defaultSearchBase);
    }

    public Flux<SearchResult> searchLdapGroups(String searchBase) throws NamingException {
        return searchLdapItems(defaultGroupFilter, defaultGroupAtts, searchBase);
    }

    public Flux<SearchResult> searchLdapGroups() throws NamingException {
        return searchLdapGroups(defaultSearchBase);
    }

}

以上逻辑的完整代码可参考工程:https://gitee.com/mxleader/quick-doc-service

我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=2ztp73q3z1gkk

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏流柯技术学院

CentOS升级Python2.7导致使用pip等命令安装模块失败

出现这个问题是因为:虽然已经把Python升级到了2.7版本,但是pip仍然是原来的版本,仍在原来python的site-package里面

1413
来自专栏我和未来有约会

flash读取XML 背景自动适应大小

var bg = new Object(); bg.bgdoc_xml = new XML(); bg.parse_XML = function() {    ...

2045
来自专栏hbbliyong

5步搭建GO环境

Easy Go Programming Setup for Windows Dec 23, 2014 I’ve had to do this more t...

4007
来自专栏java、Spring、技术分享

Spring Import 三种用法与源码解读

  最近在看Spring Cloud相关的源码,每次引入一个新的starter,发现都会加一些enable的注解,比如:@EnableDiscoveryClie...

2284
来自专栏javathings

@SpringBootApplication 的作用是什么

@SpringBootApplication 标注的类为 Spring Boot 的主配置类,Spring Boot 会运行这个类的 main 方法来启动 Sp...

8002
来自专栏蜉蝣禅修之道

Linux shell之sort命令

1893
来自专栏菩提树下的杨过

silverlight:ListBox中如何取得DateTemplate/ItemsPanelTemplate中的命名控件?

Xaml如下: <UserControl x:Class="ToolsTest.Test"     xmlns="http://schemas.microsof...

1915
来自专栏技术小黑屋

Android中一个简单有用的发现性能问题的方法

在Android中,性能优化是我们持之不懈的工作。这其中,在主线程执行耗时的任务,可能会导致界面卡顿,甚至是ANR(程序未响应)。当然Android提供了很多优...

931
来自专栏一枝花算不算浪漫

SpringBoot自定义序列化的使用方式--WebMvcConfigurationSupport

1451
来自专栏Java技术栈

Spring Boot 集成 Mybatis 实现双数据源

这里用到了Spring Boot + Mybatis + DynamicDataSource配置动态双数据源,可以动态切换数据源实现数据库的读写分离。

1802

扫码关注云+社区