【发布时间】:2018-08-20 13:37:24
【问题描述】:
我正在尝试使用 spring-boot 配置 ldap 服务器,如果我尝试读取它们的 application.yml 属性,我正在使用 application.yml 文件从代码中读取 ldap url、base、userdn、密码等总是返回 null。
以下是我的文件,请帮助我解决问题。
//应用程序.yml //---------------
spring:
profiles:
active: TEST
---
spring:
profiles: PROD
logging:
config: classpath:PROD/log4j2.yml
ldap:
url: ldap://pod-url
base: XXX
userDn: yyy
password: password
---
spring:
profiles: TEST
logging:
config: classpath:UAT/log4j2.yml
ldap:
url: ldap://ldap.forumsys.com:389
base: dc=example,dc=com
userDn: cn=read-only-admin,dc=example,dc=com
password: password
//LdapConfig.java //----------------
@Configuration
@ComponentScan(basePackages = {"com.base.package.*"})
public class LdapConfig {
@Autowired
Environment env;
@Bean
public LdapContextSource contextSource() {
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl(env.getProperty("ldap.url"));
contextSource.setBase(env.getProperty("ldap.base"));
contextSource.setUserDn(env.getProperty("ldap.userDn"));
contextSource.setPassword(env.getProperty("ldap.password"));
contextSource.afterPropertiesSet();
return contextSource;
}
@Bean
public LdapTemplate ldapTemplate() {
return new LdapTemplate(contextSource());
}
}
//从下面的文件中我将尝试使用 ldapconfig 属性
//AuthenticationServiceimpl.java //-------------------------------------------
public class AuthenticationServiceImpl implements AuthenticationService {
Logger logger = LogManager.getLogger(AuthenticationServiceImpl.class);
private LdapTemplate ldapTemplate;
private LdapContextSource ldapContextSource;
public boolean authenticateUser(String username, String password) {
ApplicationContext context = new AnnotationConfigApplicationContext(LdapConfig.class);
ldapTemplate = (LdapTemplate) context.getBean(LdapTemplate.class);
ldapContextSource = (LdapContextSource) context.getBean(LdapContextSource.class);
DirContext ctx = null;
try {
return ldapTemplate.authenticate(ldapContextSource.getBaseLdapPathAsString(), "(uid=" + username + ")",
password);
} catch (Exception e) {
logger.error("user " + username + " failed to authenticated " + e);
return false;
} finally {
if (ctx != null) {
org.springframework.security.ldap.LdapUtils.closeContext(ctx);
}
}
}
}
//我的主要应用是
@SpringBootApplication
public class Application {
public static void main(String[] args) {
Logger logger = LogManager.getLogger(Application.class);
SpringApplication.run(Application.class, args);
}
}
【问题讨论】:
-
您的代码应该可以工作。尝试转储 Spring 加载的所有属性并检查 ldap.* 属性是否具有预期值。要转储所有属性,您可以使用此处给出的代码:tekbytz.in/tutorials/spring/…。希望这会有所帮助。
-
你应该清理你的配置文件,因为缩进在 YAML 格式中很重要。在你的例子中,你做得很糟糕。也许 Spring 未能正确加载它。我建议你使用一些工具(如onlineyamltools.com/prettify-yaml)来完成它或在你的IDE中安装一个yaml美化器。
标签: java spring spring-boot ldap