我通过Spring实现LDAP认证。就我而言,我使用ActiveDirectoryLdapAuthenticationProvider
。
它看起来像这里:
private Authentication authenticate(String username, String password, HelpDescUser userDetails) {
String url = "ldap://" + ldapHost + ":" + port + "/";
ActiveDirectoryLdapAuthenticationProvider ldapProvider =
new ActiveDirectoryLdapAuthenticationProvider(domain, url, rootDn);
String filterWithName = String.format(filter, username);
ldapProvider.setSearchFilter(filterWithName);
ldapProvider.setContextEnvironmentProperties(createProperties(username, password));
ldapProvider.setConvertSubErrorCodesToExceptions(true);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, password);
Authentication authenticate;
try {
authenticate = ldapProvider.authenticate(authentication);
} catch (Exception e) {
throw new BadCredentialsException("Пользователь не авторизован (сервер LDAP не подтвердил авторизацию).");
}
if (Objects.nonNull(authenticate) && authenticate.isAuthenticated()) {
return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
} else {
throw new BadCredentialsException("Пользователь не авторизован (сервер LDAP не подтвердил авторизацию).");
}
}
private Map<String, Object> createProperties(String username, String password) {
Map<String, Object> properties = new HashMap<>();
properties.put(Context.SECURITY_PRINCIPAL, username);
properties.put(Context.SECURITY_CREDENTIALS, password);
return properties;
}
我有问题。
据我了解,身份验证架构,当我们通过用户进行身份验证时,我们还需要拥有一个技术帐户。我们通过技术帐户绑定,而不是发送用户登录名和密码,然后,我们会收到答复。但是在这种模式下,我们与同一用户绑定以进行身份验证,这是错误的-该用户可能没有绑定权限。
请给我看看使用Spring ActiveDirectoryLdapAuthenticationProvider
进行身份验证的可行解决方案?
答案 0 :(得分:1)
声明ActiveDirectoryLdapAuthenticationProvider bean时,可以使用 setContextEnvironmentProperties()方法。
例如:
@Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(null, ldapUrls, ldapBase);
setContextEnvironmentProperties(provider);
return provider;
}
private void setContextEnvironmentProperties(ActiveDirectoryLdapAuthenticationProvider provider) {
Map<String, Object> contextEnvironmentProperties = new HashMap<>();
if (StringUtils.isNotEmpty(ldapUsername)) {
contextEnvironmentProperties.put(Context.SECURITY_PRINCIPAL, ldapUsername);
}
if (StringUtils.isNotEmpty(ldapPassword)) {
contextEnvironmentProperties.put(Context.SECURITY_CREDENTIALS, ldapPassword);
}
if (!contextEnvironmentProperties.isEmpty()) {
provider.setContextEnvironmentProperties(contextEnvironmentProperties);
}
}