问题
My Problem
I am using an LdapRepository to get user information from an Ldap server. This Ldap server is also queried by Spring Security to authenticate user.
My issue is, that Spring Security is able to find and identify users, while I'm unable to find users through my LdapRepository, using the same LdapContextSource. Querying the LdapRepository in any way does not return results (null
or empty Lists).
What I have tried
- Using the ldapsearch tool directly - Works
- Using
LdapQuery
instead of thefindByUsername
method - Does not work - Testing methods like
findAll()
(CrudRepository
) - Returns an empty List - Trying to get logs from
spring-ldap
- Seems to be impossible?
Used ldapsearch command: ldapsearch -x -H ldaps://<domain> -b o=<org> uid=<uid>
Viewing the traffic in Wireshark (using ldap
instead of ldaps
) looks like no query is executed by the LdapRepository at all, the connection just opens and closes with 0 results.
Relevant code
Configuration of LdapContextSource
@Bean
public LdapContextSource contextSource() {
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl("ldaps://<domain>");
contextSource.setBase("o=<org>");
return contextSource;
}
SecurityConfiguration
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final AuthenticationManagerBuilder authenticationManagerBuilder;
private final LdapContextSource ldapContext;
public SecurityConfiguration(AuthenticationManagerBuilder authenticationManagerBuilder, LdapContextSource ldapContext) {
this.authenticationManagerBuilder = authenticationManagerBuilder;
this.ldapContext = ldapContext;
}
@PostConstruct
public void init() {
try {
authenticationManagerBuilder
.ldapAuthentication()
.contextSource(ldapContext)
.userSearchFilter("(uid={0})");
} catch (Exception e) {
throw new BeanInitializationException("Security configuration failed", e);
}
}
}
UserRepository
@Repository
public interface UserRepository extends LdapRepository<User> {
User findByUsername(String username);
List<User> findByUsernameLikeIgnoreCase(String username);
}
User
@Entry(
objectClasses = {})
public class User {
@Id
private Name id;
@Attribute(name = "uid", readonly = true)
private String username;
public Name getId() {
return id;
}
public String getUsername() {
return username;
}
}
回答1:
I found the solution.
Spring seems to assume the objectClass
of User
is User
, if it is not set explicitly. Setting the correct objectClasses fixes this issue.
来源:https://stackoverflow.com/questions/48380693/spring-ldaprepository-returns-no-results-while-spring-security-works