在Spring Embedded LDAP中存储二进制项



我希望你们中的某个人能帮助我解决Spring Embedded LDAP的问题。我在单元测试中使用嵌入式LDAP来模拟高效的Active Directory,但存在一个问题。

LDAP设置正确(启动(,并预先填充了schema.ldif

问题来了:

在Active Directory中,是用户处的二进制属性,它将在用户代表类中通过LdapTemplate读取为byte[]。在Active Directory中,一切正常。但在Spring嵌入式LDAP中,字段总是一个String,当我尝试读取它时,我会得到一个ConversionException

有没有任何方法可以在LDIF(或其他地方(中告诉Spring这个属性是一个二进制属性,以便将值存储为byte[]或将字符串返回为byte]]?

我尝试将它添加为使用::表示法的Base64编码字符串,也添加为使用:<表示法的文件。但这两种方式都将其作为字符串存储在LDAP中。

我自己解决了这个问题。如果有人再次出现同样的问题,这里是我的解决方案:

问题不在于属性存储为String,而是客户端环境在使用嵌入式LDAP时配置错误。

在客户端中,通过application.properties设置环境属性,如下所示:spring.ldap.base-environment.java.naming.ldap.attributes.binary=propertyName

当ldap客户端的ContextSource初始化时,该属性将被放入上下文中,并且该属性将解析为二进制。

但是客户端的CCD_ 10是用CCD_。因此,如果ContextSource的bean已经存在,则该bean将不会再次初始化。

如果使用嵌入式LDAP,它会在客户端之前创建自己的ContextSource,因此客户端使用与服务器相同的ContextSource。在此ContextSource中,不存在binary属性。

这就是我的问题的原因,房产没有设置。

无法通过application.properties.将属性设置为环境属性

我的解决方案是ApplicationListener,它在初始化后将属性设置为源。

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.ldap.core.support.AbstractContextSource;
import org.springframework.stereotype.Component;
import java.util.Collections;
/**
* This optimizer is necessary because the property cannot be set otherwise.
* The LDAP Client initialises it`s ContextSource (with the property from the application.properties) on ConditionalOnMissingBean.
* By using the embedded LDAP the bean is no longer missing and the ContextSource from the embedded LDAP is used.
* This bean does not use any properties for the environment.
* So we are using this optimizer to set the properties afterwards.
*/
@Component
public class LdapContextSourceOptimizer implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
AbstractContextSource contextSource = contextRefreshedEvent.getApplicationContext().getBean(AbstractContextSource.class);
contextSource.setBaseEnvironmentProperties(Collections.singletonMap("java.naming.ldap.attributes.binary", "objectGUID"));
contextSource.afterPropertiesSet();
}
}

最新更新