[英]The Spring Boot way to do LDAP authentication
I have the following working codes that can authenticate a user with LDAP.我有以下工作代码,可以使用 LDAP 对用户进行身份验证。 As you can see, it's very simple.
如您所见,它非常简单。 But how can I do the same thing the Spring Boot way?
但是我怎样才能用 Spring 引导方式做同样的事情呢?
try {
Hashtable<String, Object> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, “ldaps://xxxxxxxx.abcgroup.xyz.com:636”);
env.put(Context.SECURITY_AUTHENTICATION, "simple"); // fixed value
env.put(Context.SECURITY_PRINCIPAL, “myid@abcgroup.xyz.com”);
env.put(Context.SECURITY_CREDENTIALS, "mypassword");
new InitialDirContext(env);
// authentication successful.
} catch (Exception exception) {
// authentication failed.
}
Firstly you should write your Connection information in a Configuration file,for example a ldap.yml file.首先,您应该将连接信息写入配置文件,例如 ldap.yml 文件。
ldap:
url: ldap://XXXXXXX:389/
root: cn=root,dc=root,dc=com
userDn: cn=root,dc=root,dc=com
password: XXXXXX
baseDN: dc=root,dc=com
clean: true
pooled: false
And then using these attribute inject a ldaptemplate bean,this is a propeties class:然后使用这些属性注入一个 ldaptemplate bean,这是一个属性 class:
@ConfigurationProperties(prefix = "ldap")
public class LdapProperties {
private String url;
private String userDn;
private String password;
private String baseDN;
private String clean;
private String root;
private boolean pooled = false;
}
this is a Configuration class:这是一个配置 class:
@Configuration
@EnableConfigurationProperties({LdapProperties.class})
public class LdapConfiguration {
@Autowired
LdapProperties ldapProperties;
@Bean
public LdapTemplate ldapTemplate() {
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl(ldapProperties.getUrl());
contextSource.setUserDn(ldapProperties.getUserDn());
contextSource.setPassword(ldapProperties.getPassword());
contextSource.setPooled(ldapProperties.getPooled());
contextSource.setBase(ldapProperties.getBaseDN());
contextSource.afterPropertiesSet();
return new LdapTemplate(contextSource);
}
}
And then you can use @Autowired Annotations.This annotation allows Spring to resolve and inject collaborating beans into your bean.然后您可以使用@Autowired Annotations。此注解允许 Spring 解析协作 bean 并将其注入您的 bean。
@Autowired
LdapTemplate ldapTemplate;
Using ldapTemplate you could do CRUD like a relational database.of course you can do authentication things.使用 ldapTemplate 您可以像关系数据库一样执行 CRUD。当然您也可以执行身份验证。 This is my first time answer questions in stackoverflow,I welcome you to point out my mistakes.
这是我第一次在stackoverflow回答问题,欢迎大家指出我的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.