我正在使用 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;
}
}