Spring Boot集成AD域实现统一用户认证

Spring Boot集成AD域实现统一用户认证
2. Spring Boot集成LDAP配置
在pom.xml中添加Maven依赖



  org.springframework.boot
  spring-boot-starter-data-ldap



  org.springframework.boot
  spring-boot-starter-data-jpa

2.1 方法1. 自定义LdapTemplate配置
3. 在项目应用配置文件application.yml中添加AD域配置

# AD Config
ldap:
  url: "ldap://192.168.1.1:389"
  base: DC=example,DC=com
  userDn: "[email protected]"
  userPwd: 123456
  referral: follow
  domainName: "%[email protected]"
  1. 在Spring Boot中启动AD域配置
package com.garyond.hurricane.myservice.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;

@Configuration
public class LdapConfig {

    @Value("${ldap.url}")
    private String ldapUrl;

    @Value("${ldap.base}")
    private String ldapBase;

    @Value("${ldap.userDn}")
    private String ldapUserDn;

    @Value("${ldap.userPwd}")
    private String ldapUserPwd;

    @Value("${ldap.referral}")
    private String ldapReferral;


    /*
     * SpringLdap的javaConfig注入方式
     */
    @Bean
    public LdapTemplate ldapTemplate() {
        return new LdapTemplate(contextSourceTarget());
    }
    
    /*
     * SpringLdap的javaConfig注入方式
     */
    @Bean
    public LdapContextSource contextSourceTarget() {
        LdapContextSource ldapContextSource = new LdapContextSource();

        ldapContextSource.setUrl(ldapUrl);
        ldapContextSource.setBase(ldapBase);
        ldapContextSource.setUserDn(ldapUserDn);
        ldapContextSource.setPassword(ldapUserPwd);
        ldapContextSource.setReferral(ldapReferral);
        return ldapContextSource;
    }
}
  1. 使用LdapTemplate操作LDAP
@Service
public class LdapServiceImpl implements LdapService {

    @Autowired
    private LdapTemplate ldapTemplate;

    @Value("${ldap.domainName}")
    private String ldapDomainName;

    @Value("${ldap.base}")
    private String ldapBaseDn;
    
    /**
     * 获取部门列表
     */
    @Override
    public List getDepartmentList(String ldapBase, Filter filter) {
        return ldapTemplate.search(ldapBase, filter.encode(), new AttributesMapper() {
            @Override
            public String mapFromAttributes(Attributes attr) throws NamingException {
                String distinguishedName = (String)attr.get("distinguishedName").get();
                distinguishedName = StringUtils.substringBefore(distinguishedName,ldapBaseDn);

                return StringUtils.substringBeforeLast(distinguishedName, ",");
            }
        });
    }
    
    /**
     * 获取用户列表
     */
    @Override
    public List getPersonList(String ldapBase, Filter filter) {
        return ldapTemplate.search(ldapBase, filter.encode(), new AttributesMapper() {
            @Override
            public User mapFromAttributes(Attributes attr) throws NamingException {
                User person = new User();
                String distingugihedName = (String)attr.get("distinguishedName").get();
                person.setUserName((String)attr.get("username").get());
                person.setEmail((String)attr.get("mail").get());
                person.setRealName((String)attr.get("name").get());
                if (null != attr.get("mobile")) {
                    person.setMobile((String) attr.get("mobile").get());
                }
                if (null != attr.get("telephoneNumber")) {
                    person.setPhone((String) attr.get("telephoneNumber").get());
                }
                person.setLdapFlag(1);
                String departmentName = StringUtils.substringAfter(distingugihedName.split(",")[1], "OU=");
                person.setUnitName(departmentName);
                return person;
            }
        });
    }
    
    /*
     * 身份认证
     */
    @Override
    public boolean authenticate(String userName, String password) {

        //String userDomainName = getDnForUser(userName);

        String userDomainName = String.format(ldapDomainName, userName);

        DirContext ctx = null;

        try {
            ctx = ldapTemplate.getContextSource().getContext(userDomainName,password);
            return true;

        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            LdapUtils.closeContext(ctx);
        }

        return false;
    }
}

2.2 方法2. 使用Spring Data Ldap自动配置

  1. 在项目应用配置文件application.yml中添加AD域配置

使用Spring Data Ldap项目包连接LDAP服务器可以采用以下的配置方式:

spring:
    ldap:
       urls: ldap://192.168.1.1:389
       base: DC=example,DC=com
       username: "[email protected]"
       password: 123456
  1. 启用Ldap配置

在Spring Boot主应用程序中添加@EnableLdapRepositories注解

@SpringBootApplication
@EnableLdapRepositories
public class MyServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyServiceApplication.class, args);
    }
}
  1. 定义LDAP中属性与Java中所定义实体的关系映射
@Data
@Entry(base = "ou=XX公司,dc=example,dc=com", objectClasses = {"OrganizationalPerson", "Person", "top"})
public class User {

    @Id
    private Name id;

    @DnAttribute(value = "distiguishedName")
    private String distinguishedName;

    @Attribute(name = "cn")
    private String commonName;

    @Attribute(name = "sn")
    private String suerName;

    @Atrributed(name = "email")
    private String email;

    ... ...

}
  1. 创建LDAP对应的DAO操作
/**
 * UserDao继承CrudRepository接口实现基于Ldap的增删改查操作
 */
public interface UserDao extends CrudRepository {}
``
5. 创建单元测试用例读取所有用户的信息

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

@Autowired
private UserDao userDao;

@Test
public void findAll() throws Exception {
    userDao.findAll().forEach(p -> {
        System.out.println("Distigushed Name:" + p.distinguishedName);
    });
}

}


你可能感兴趣的:(Spring Boot集成AD域实现统一用户认证)