spring-security Spring Security 5.7 LdapUserDetailsMapper权限为空

jaxagkaj  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(143)

在升级到Sping Boot 2.7.2(Spring Security 5.7.2)之前,以下LDAP身份验证配置起作用。
Ldap相关应用程序属性:

spring.ldap.urls = ldaps://ldap-one:636, ldaps://ldap-two:636, ldaps://ldap-three:636
spring.ldap.base =******
spring.ldap.username =******
spring.ldap.password =******

安全配置代码段:

@Value("${active.directory.domain}")
private String activeDirectoryDomain;

@Value("#{'${spring.ldap.urls}'.replaceAll(',', '')}") 
private String activeDirectoryLdapUrls;

@Autowired 
private CustomLdapUserDetailsMapper customLdapUserDetailsMapper;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(activeDirectoryDomain, activeDirectoryLdapUrls);
  provider.setSearchFilter("(&(objectClass=user)(sAMAccountName={1}))");
  provider.setUserDetailsContextMapper(customLdapUserDetailsMapper);
  auth.authenticationProvider(provider);
}

我们的CustomLdapUserDetailsMapper中的ldapAuthorities参数包含用户所属的所有组名:

@Component
public class CustomLdapUserDetailsMapper extends LdapUserDetailsMapper implements Serializable {

  @Override
  public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> ldapAuthorities) {
    User user = new User();
    user.setUserDetails(super.mapUserFromContext(ctx, username, ldapAuthorities));
    user.setFirstName(ctx.getStringAttribute("givenName"));
    user.setLastName(ctx.getStringAttribute("sn"));
    user.setEmail(ctx.getStringAttribute("mail"));
    return user;
  }
}

一切都很顺利。
尝试根据Spring Security 5.7文档更新安全配置,以:

@Bean
public AuthenticationManager getLdapAuthenticationManager(BaseLdapPathContextSource contextSource, CustomLdapUserDetailsMapper customLdapUserDetailsMapper) {
  LdapBindAuthenticationManagerFactory factory = new LdapBindAuthenticationManagerFactory(contextSource);
  factory.setUserSearchFilter("(&(objectClass=user)(sAMAccountName={0}))");
  factory.setUserDetailsContextMapper(customLdapUserDetailsMapper);
  return factory.createAuthenticationManager();
}

我发现CustomLdapUserDetailsMapper中的ldapAuthorities现在是空的(我依赖于在配置SecurityFilterChain时存在的特定权限-未显示)。
如何解决此问题?

hwamh0ep

hwamh0ep1#

我只是需要继续阅读文件(该死的)!
解决方案是公开一个与原始配置完全相同的ActiveDirectoryLdapAuthenticationProvider bean:

@Bean
public ActiveDirectoryLdapAuthenticationProvider authenticationProvider( @Value("${active.directory.domain}") String domain, @Value("#{'${spring.ldap.urls}'.replaceAll(',', '')}") String urls, CustomLdapUserDetailsMapper customLdapUserDetailsMapper) {
  ActiveDirectoryLdapAuthenticationProvider  authProvider = new ActiveDirectoryLdapAuthenticationProvider(domain, urls);
  authProvider.setSearchFilter("(&(objectClass=user)(sAMAccountName={1}))");
  authProvider.setUserDetailsContextMapper(customLdapUserDetailsMapper);
  return authProvider;
}

相关问题