java - Spring Security 工作时 Spring LdapRepository 不返回结果

标签 java spring spring-data spring-ldap spring-repositories

我的问题

我正在使用 LdapRepository 从 Ldap 服务器获取用户信息。 Spring Security 也会查询此 Ldap 服务器来验证用户身份。

我的问题是,Spring Security 能够查找和识别用户,而我无法使用相同的 LdapContextSource 通过 LdapRepository 查找用户。以任何方式查询 LdapRepository 都不会返回结果( null 或空列表)。

我尝试过的

  • 使用ldapsearch直接使用工具 - 有效
  • 使用LdapQuery而不是 findByUsername方法 - 不起作用
  • 测试方法如findAll() ( CrudRepository ) - 返回一个空列表
  • 尝试从 spring-ldap 获取日志-Seems to be impossible?

使用的 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;
    }
}

最佳答案

我找到了解决方案。

如果未显式设置,Spring 似乎假定 UserobjectClassUser。设置正确的对象类可以解决此问题。

关于java - Spring Security 工作时 Spring LdapRepository 不返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48380693/

相关文章:

java - Hibernate 左外连接

java - Android 位图变为空

java - 使用spring的条件bean

java - 无法使用 SpringMVC 通过 Hibernate 将 ItemDetail 列表 ie.List<ItemDetail> (OBJECT) 插入 MySQL 数据库字段

java - spring-data-jdbc 错误未找到类所需的标识符属性

java - spring data mongodb 映射动态字段

java - 如何编辑 MANIFEST 文件以管理员身份运行 JAR? ( window )

javascript - BIRT - getPersistentGlobalVariable 仅给出最后一行

java - maven:在 war/web-inf/classes 中添加类作为对 Jar 模块的依赖

spring - Hibernate Search 的使用、何时使用以及为什么