【发布时间】:2014-09-27 23:01:40
【问题描述】:
我在 Spring Boot 应用程序中使用 Spring Security 和 spring-security-ldap 进行身份验证。
我想实现一个LdapAuthoritiesPopulator,它从 LDAP 服务器中查找一些条目来决定用户的角色。这些条目不在用户之下,因此提供给getGrantedAuthorities 方法的userData 对象是不够的。 (我无法控制 LDAP 服务器,因此无法将角色添加到用户条目)。
我考虑将 Spring Security 在调用 auth.ldapAuthentication().contextSource() 时创建的 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;
}
}
【问题讨论】:
标签: spring-security spring-boot spring-ldap spring-security-ldap