关于springboot集成ldap

1. 准备

1.1 导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-ldap</artifactId>
        </dependency>

1.2 修改配置

spring:
  ldap:
    urls: ldap://192.168.16.34:389
    base: dc=testldap,dc=com
    username: dn=admin,dc=testldap,dc=com
    password: 123456

2. 使用

Person中字段为需要从Ldap中查询的数据字段,利用注解@Attribute(name=“xx”)进行注解,Entry中定义的objectClass和base为Ldap中数据资源的定位信息。查询的时候可以作为返回对象来接收数据。


@Data
@ToString
@Entry(objectClasses = {"bicPersonExt", "bicPerson"}, base = "ou=person,dc=coreservice")
public class Person {
    /**
     * 主键
     */
    @Attribute
    private String personId;

    /**
     * 人员姓名
     */
    @Attribute(name = "cn")
    private String personName;
    /**
     * 组织ID
     */
    @Attribute(name = "orgId")
    private String orgId;
    /**
     * 性别
     */
    @Attribute(name = "sex")
    private Integer sex;
    /**
     * 电话
     */
    @Attribute(name = "mobile")
    private String mobile;
    /**
     * 邮箱
     */
    @Attribute(name = "email")
    private String email;
    /**
     * 工号
     */
    @Attribute(name = "jobNo")
    private String jobNo;
    /**
     * 学号
     */
    @Attribute(name = "studentId")
    private String studentId;

    /**
     * 证件类型
     */
    @Attribute(name = "certType")
    private Integer certType;
    /**
     * 证件号码
     */
    @Attribute(name = "certificateNo")
    private String certNo;

    @Attribute
    protected Date createTime;

    /**
     * 更新时间
     */
    @Attribute
    protected Date updateTime;
    /**
     * 状态
     */
    @Attribute
    protected Integer status;

    @Attribute
    protected Integer disOrder;

    /**
     * 工作单位
     */
    @Attribute
    private String company;
}

public interface IPersonRepo {

    void setLdapTemplate(LdapTemplate ldapTemplate);

    List<String> getAllPersonNames();

    List<String> getAllPersonNamesWithTraditionalWay();

    List<Person> getAllPersons();

    Person findPersonWithDn(String dn);

    List<String> getPersonNamesByOrgId(String orgId);
}
public class PersonRepoImpl implements IPersonRepo {

    private LdapTemplate ldapTemplate;

    @Override
    public void setLdapTemplate(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;
    }

    /**
     * 查询部分字段集合
     * @return
     */
    @Override
    public List<String> getAllPersonNames() {
        return ldapTemplate.search(
                query().where("objectclass").is("person"), (AttributesMapper<String>) attrs -> (String) attrs.get("cn").get());
    }

    /**
     * 传统LDAP查询方式
     * @return
     */
    @Override
    public List<String> getAllPersonNamesWithTraditionalWay() {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://10.33.47.7:7003/dc=platform,dc=xxx,dc=com");
        env.put(Context.SECURITY_PRINCIPAL, "ou=acs,ou=componentaccounts,dc=platform,dc=xxx,dc=com");
        env.put(Context.SECURITY_CREDENTIALS, "UlAwRkYl");
        DirContext ctx;
        try {
            ctx = new InitialDirContext(env);
        } catch (NamingException e) {
            throw new RuntimeException(e);
        }

        List<String> list = new LinkedList<String>();
        NamingEnumeration results = null;
        try {
            SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            results = ctx.search("", "(objectclass=person)", controls);
            while (results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();
                Attributes attributes = searchResult.getAttributes();
                Attribute attr = attributes.get("cn");
                String cn = attr.get().toString();
                list.add(cn);
            }
        } catch (NameNotFoundException e) {
            // The base context was not found.
            // Just clean up and exit.
        } catch (NamingException e) {
            //throw new RuntimeException(e);
        } 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;
    }

    /**
     * 查询对象映射集合
     * @return
     */
    @Override
    public List<Person> getAllPersons() {
        return ldapTemplate.search(query()
                .where("objectclass").is("person"), new PersonAttributesMapper());
    }

    /**
     * 根据DN查询指定人员信息
     * @param dn
     * @return
     */
    @Override
    public Person findPersonWithDn(String dn) {
        return ldapTemplate.lookup(dn, new PersonAttributesMapper());
    }

    /**
     * 组装查询语句
     * @param orgId
     * @return
     */
    @Override
    public  List<String> getPersonNamesByOrgId(String orgId) {
        LdapQuery query = query()
                .base("ou=person,dc=coreservice")
                .attributes("cn", "sn")
                .where("objectclass").is("person")
                .and("orgId").is(orgId);
        return ldapTemplate.search(query,(AttributesMapper<String>) attrs -> (String) attrs.get("cn").get());
    }

}
public class PersonAttributesMapper implements AttributesMapper<Person> {
    /**
     * Map Attributes to an object. The supplied attributes are the attributes
     * from a single SearchResult.
     *
     * @param attrs attributes from a SearchResult.
     * @return an object built from the attributes.
     * @throws NamingException if any error occurs mapping the attributes
     */
    @Override
    public Person mapFromAttributes(Attributes attrs) throws NamingException {
        Person person = new Person();
        person.setPersonName((String)attrs.get("cn").get());
        person.setOrgId((String)attrs.get("orgId").get());
        return person;
    }
}

测试用例

@RunWith(SpringRunner.class)
@SpringBootTest(classes={Chapter3ApplicationTest.class})
public class LdapTest {

    @Autowired
    private LdapTemplate ldapTemplate;

    private  PersonRepoImpl personRepo;

    @Before
    public void init(){
        personRepo = new PersonRepoImpl();
        personRepo.setLdapTemplate(ldapTemplate);
    }

    @Test
    public void ldapRestTestPart1(){
        // 查询所有人员名称
        //personRepo.getAllPersonNames().forEach(p-> System.out.println(p));
        //荣禧
        //荣耀
        //feng_p1
        //fengzi_0917_1
        //....
        // 查询所有人员集合(指定字段映射)
        //personRepo.getAllPersons().forEach(p-> System.out.println(p.toString()));
        //Person(personId=null, personName=fengzi_0917_7, orgId=14ed2744-fbd4-4868-8ebc-6b0b94d5ae60, sex=null, mobile=null, email=null, jobNo=null, studentId=null, certType=null, certNo=null, createTime=null, updateTime=null, status=null, disOrder=null, company=null)
        //Person(personId=null, personName=fengzi_0917_104, orgId=14ed2744-fbd4-4868-8ebc-6b0b94d5ae60, sex=null, mobile=null, email=null, jobNo=null, studentId=null, certType=null, certNo=null, createTime=null, updateTime=null, status=null, disOrder=null, company=null)

        //根据dn查询
        System.out.println(personRepo.findPersonWithDn("ou=person,dc=coreservice,dc=platform,dc=xxx,dc=com").toString());

        //根据组织ID查询人员
        //personRepo.getPersonNamesByOrgId("14ed2744-fbd4-4868-8ebc-6b0b94d5ae60").forEach(System.out::println);
        //feng_0925_4687
        //feng_0925_4693
        //...

        //传统查询方式
        //personRepo.getAllPersonNamesWithTraditionalWay().forEach(System.out::println);
        //荣禧
        //荣福
        //feng_p1
        //fengzi_0917_1
        //....

    }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在 Spring Boot 中,可以使用 Spring LDAP 来实现 LDAP 认证。具体步骤如下: 1. 配置 pom.xml,引入 Spring LDAP 相关依赖: ```xml <dependency> <groupId>org.springframework.ldap</groupId> <artifactId>spring-ldap-core</artifactId> <version>${spring-ldap.version}</version> </dependency> ``` 2. 配置 application.yml,设置 LDAP 连接信息: ```yaml spring: ldap: urls: ldap://localhost:389 base: dc=my-domain,dc=com username: cn=Manager,dc=my-domain,dc=com password: password ``` 3. 实现 LdapUserDetailsMapper,将 LDAP 用户信息映射为 Spring Security User 对象: ```java @Component public class LdapUserDetailsMapper implements UserDetailsContextMapper { @Override public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) { String password = (String) ctx.getObjectAttribute("userPassword"); List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (GrantedAuthority authority : authorities) { grantedAuthorities.add(new SimpleGrantedAuthority(authority.getAuthority())); } return new User(username, password, grantedAuthorities); } @Override public void mapUserToContext(UserDetails user, DirContextAdapter ctx) { throw new UnsupportedOperationException("Not supported yet."); } } ``` 这里将 LDAP 中的 "userPassword" 属性作为密码,LDAP 中的权限信息作为 Spring Security 的 GrantedAuthority 对象,最终将它们封装为一个 User 对象。 4. 配置 WebSecurityConfigurerAdapter,实现 LDAP 认证: ```java @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private LdapUserDetailsMapper ldapUserDetailsMapper; @Autowired private Environment env; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() .and() .formLogin() .and() .logout(); http.csrf().disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.ldapAuthentication() .userSearchBase(env.getProperty("spring.ldap.user-search-base")) .userSearchFilter(env.getProperty("spring.ldap.user-search-filter")) .groupSearchBase(env.getProperty("spring.ldap.group-search-base")) .groupSearchFilter(env.getProperty("spring.ldap.group-search-filter")) .contextSource() .url(env.getProperty("spring.ldap.urls")) .managerDn(env.getProperty("spring.ldap.username")) .managerPassword(env.getProperty("spring.ldap.password")) .and() .userDetailsContextMapper(ldapUserDetailsMapper); } } ``` 这样就可以通过 LDAP 认证来控制访问权限了。在这个例子中,请求 "/admin/**" 的用户需要拥有 ADMIN 角色,请求 "/user/**" 的用户需要拥有 USER 角色,其他请求需要认证通过即可访问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值