0

我正在使用 Spring Security 并spring-security-ldap在 Spring Boot 应用程序中进行身份验证。

我想实现一个LdapAuthoritiesPopulator从 LDAP 服务器中查找一些条目来决定用户角色的方法。这些条目不在用户之下,所以userData提供给getGrantedAuthorities方法的对象是不够的。(我无法控制 LDAP 服务器,因此无法将角色添加到用户条目)。

我考虑将ContextSource调用时创建的 Spring Security注入auth.ldapAuthentication().contextSource()(参见下面代码中的 (1))到LdapAuthoritiesPopulator. 但这不起作用,因为LdapAuthoritiesPopulator是在 之前创建的WebSecurityConfigurerAdapter,所以ContextSource还不存在。

我的WebSecurityConfigurerAdapter包含以下方法:

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {

    auth.ldapAuthentication()
            .contextSource() // (1)
                .url("ldap://example.org/o=organization")
                .and()
            .ldapAuthoritiesPopulator(ldapAuthoritiesPopulator)
            .userSearchFilter("uid={0}");
}

ldapAuthoritiesPopulator是自动装配的,该类目前是一个虚拟实现,只需添加ROLE_USER

@Component
public class CustomLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator {

    @Override
    public Collection<? extends GrantedAuthority> getGrantedAuthorities(
        DirContextOperations userData, String username) {

        // I want to look up some entries in LDAP here, so I need a ContextSource
        // but I can't inject it because it does not exist when this bean is created

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("USER"));
        return authorities;
    }
}
4

1 回答 1

0

在应用程序运行之前,您不需要填充角色(我想)。因此,可行的一件事是注入ApplicationContext而不是注入ContextSource并懒惰地查找后者。如果可行的话,可能会有一辆带有@Lazy.

于 2014-08-06T05:14:12.300 回答