我在 spring-boot 应用程序中使用 LDAP 身份验证(基于注释的配置)。我想自定义 UserDetails 对象。默认 UserDetails 实现是LdapUserDetailsImpl。我想扩展这个类并添加一些额外的 iterfaces 并绑定到 spring-security 中。我的配置类:
@Configuration
protected static class AuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter {
@Autowired
private UserService userService;
@Autowired
private Environment env;
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
AuthMethod authMethod = AuthMethod.valueOf(env.getRequiredProperty("auth_method"));
switch (authMethod) {
case LDAP:
auth.ldapAuthentication()
.userDnPatterns(env.getRequiredProperty("ldap.user_dn_patterns"))
.groupSearchBase(env.getRequiredProperty("ldap.group_search_base"))
.contextSource()
.url(env.getRequiredProperty("ldap.url"));
break;
default:
auth.userDetailsService(userService);
break;
}
}
@Bean
public LdapContextSource contextSource () {
LdapContextSource contextSource= new LdapContextSource();
contextSource.setUrl(env.getRequiredProperty("ldap.url"));
contextSource.setUserDn(env.getRequiredProperty("ldap.user"));
contextSource.setPassword(env.getRequiredProperty("ldap.password"));
contextSource.afterPropertiesSet();
return contextSource;
}
}
UserService 是自定义的身份验证方法(它是数据库/jpa 身份验证)。UserDetails 访问器(当 auth 方法是 LDAP 时,它返回 LdapUserDetailsImpl 对象):
@Component("activeUserAccessor")
public class ActiveUserAccessorImpl implements ActiveUserAccessor
{
public UserDetails getActiveUser()
{
return (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}
谢谢您的帮助。