Spring LdapRepository не возвращает результатов, пока работает Spring Security

Моя проблема

Я использую LdapRepository для получения информации о пользователе с сервера Ldap. Spring Security также запрашивает этот сервер Ldap для аутентификации пользователя.

Моя проблема в том, что Spring Security может находить и идентифицировать пользователей, в то время как я не могу найти пользователей через свой LdapRepository, используя тот же LdapContextSource. Любые запросы к LdapRepository не возвращают результатов (null или пустых списков).

Что я пробовал

  • Непосредственное использование инструмента ldapsearchработает
  • Использование LdapQuery вместо метода findByUsername - не работает
  • Методы тестирования, такие как findAll() (CrudRepository) — возвращает пустой список
  • Попытка получить журналы от spring-ldap — Кажется, это невозможно?

Используемая команда ldapsearch: ldapsearch -x -H ldaps://<domain> -b o=<org> uid=<uid>

Просмотр трафика в Wireshark (с использованием ldap вместо ldaps) выглядит так, как будто запрос LdapRepository вообще не выполняется, соединение просто открывается и закрывается с 0 результатами.

Соответствующий код

Конфигурация LdapContextSource

@Bean
public LdapContextSource contextSource() {
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl("ldaps://<domain>");
    contextSource.setBase("o=<org>");
    return contextSource;
}

Конфигурация безопасности

@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);
        }
    }
}

Пользовательский репозиторий

@Repository
public interface UserRepository extends LdapRepository<User> {
    User findByUsername(String username);
    List<User> findByUsernameLikeIgnoreCase(String username);
}

Пользователь

@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;
    }
}

person Joba    schedule 22.01.2018    source источник


Ответы (1)


Я нашел решение.

Spring, кажется, предполагает, что objectClass из User равно User, если он не установлен явно. Установка правильных объектных классов устраняет эту проблему.

person Joba    schedule 22.01.2018