通过Active Directory LDAP使用Spring-Security进行身份验证



我无法使用真正的活动目录进行身份验证,让我更好地解释一下,我尝试使用 spring.io 提出的示例进行身份验证,在内部服务启动时没有任何问题。 参考 https://spring.io/guides/gs/authenticating-ldap/

我试图通过插入我的活动目录的配置来修改下面的代码,但没有成功。您能否指导我或向我展示一个真实案例,其中无需使用示例中的内部服务即可建立真正的连接?我在网上看了看,但发现所有与官方示例相似的内容,没有任何真实案例

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource()
.url("ldap://localhost:8389/dc=springframework,dc=org")
.and()
.passwordCompare()
.passwordEncoder(new LdapShaPasswordEncoder())
.passwordAttribute("userPassword");
}

错误显示: LDAP 处理期间发生未分类异常;嵌套异常是 javax.naming.命名异常:[LDAP:错误代码 1 - 000004DC:LdapErr:DSID-0C0907C2,注释:要执行此操作,必须在连接上完成成功的绑定。, 数据 0, v2580

是的,通过LDAP进行身份验证太痛苦了。为了能够对AD执行身份验证,您需要使用ActiveDirectoryLdapAuthenticationProvider。 下面是工作示例:

@Override
protected void configure(AuthenticationManagerBuilder auth) {
ActiveDirectoryLdapAuthenticationProvider adProvider =
new ActiveDirectoryLdapAuthenticationProvider("domain.com", "ldap://localhost:8389");
adProvider.setConvertSubErrorCodesToExceptions(true);
adProvider.setUseAuthenticationRequestCredentials(true);
auth.authenticationProvider(adProvider);
}

为了节省您的时间,请阅读以下内容,这非常重要: AD 身份验证文档

我在这里找到了一个示例,它很有用:

https://github.com/sachin-awati/Mojito/tree/master/webapp/src/main/java/com/box/l10n/mojito/security

您可以选择实现UserDetailsContextMapperImpl,如果在 Active Directory 查找期间未找到用户,则覆盖mapUserFromContext以创建UserDetails对象 -loadUserByUsername

@Component
public class UserDetailsContextMapperImpl implements UserDetailsContextMapper {
@Override
public UserDetails mapUserFromContext(DirContextOperations dirContextOperations, String username, Collection<? extends GrantedAuthority> authorities) {
UserDetails userDetails = null;
try {
userDetails = userDetailsServiceImpl.loadUserByUsername(username);
} catch (UsernameNotFoundException e) {
String givenName = dirContextOperations.getStringAttribute("givenname");
String surname = dirContextOperations.getStringAttribute("sn");
String commonName = dirContextOperations.getStringAttribute("cn");
userDetails = userDetailsServiceImpl.createBasicUser(username, givenName, surname, commonName);
}
return userDetails;
}

确保您使用的是ActiveDirectoryLdapAuthenticationProviderspring 安全类,因为与其他 LDAP 服务器相比,Active Directory 有自己的细微差别。您可能需要在安全配置类中使用@EnableGlobalAuthentication注释,因为您可能有多个AuthenticationManagerBuilder,这会让事情变得非常混乱。

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
ActiveDirectoryLdapAuthenticationProvider adProvider =
new ActiveDirectoryLdapAuthenticationProvider("domain.com", "ldap://primarydc.domain.com:389");
adProvider.setConvertSubErrorCodesToExceptions(true);
adProvider.setUseAuthenticationRequestCredentials(true);
auth.authenticationProvider(adProvider);
}

更多细节在这里: https://github.com/spring-projects/spring-security/issues/4324 https://github.com/spring-projects/spring-security/issues/4571

最新更新