How to obtain all LDAP groups in spring security
How to obtain all Active Directory groups (Not just related to a current user)? I'm using spring security ldap. Could you provide some examples?
Spring Security LDAP is great if you want to authenticate users, but if you just need to query LDAP (in this case for all groups), then Spring LDAP (not to be confused with Spring Security LDAP) is better suited for your purposes.
Example:
import static org.springframework.ldap.query.LdapQueryBuilder.query;
LdapTemplate ldapTemplate; // Injected via Spring
// Using Java 8 lambda expressions
ldapTemplate.search(
query().where("objectclass").is("group"),
(AttributesMapper<String>) attributes -> attributes.get("cn").get().toString()
);
What you can do is write an implementation of LdapAuthoritiesPopulator
that matches the DefaultLdapAuthoritiesPopulator
implementation with an extra method to retrieve all roles.
public class ExtendedLdapAuthoritiesPopulator
implements LdapAuthoritiesPopulator {
// Copy implementation of DefaultLdapAuthoritiesPopulator (omitted).
private String allAuthorityFilter
= "(&(objectClass=group)(objectCategory=group))";
public void setAllAuthorityFilter(String allAuthorityFilter) {
Assert.notNull(allAuthorityFilter,
"allAuthorityFilter must not be null");
this.allAuthorityFilter = allAuthorityFilter;
}
public final Collection<GrantedAuthority> getAllAuthorities() {
if (groupSearchBase == null) {
return new HashSet<>();
}
Set<GrantedAuthority> authorities = new HashSet<>();
if (logger.isDebugEnabled()) {
logger.debug("Searching for all roles with filter '"
+ allAuthorityFilter + "' in search base '"
+ groupSearchBase + "'");
}
Set<String> roles = ldapTemplate.searchForSingleAttributeValues(
groupSearchBase,
allAuthorityFilter,
new String[0],
groupRoleAttribute);
if (logger.isDebugEnabled()) {
logger.debug("Roles from search: " + roles);
}
for (String role : roles) {
if (convertToUpperCase) {
role = role.toUpperCase();
}
authorities.add(new SimpleGrantedAuthority(rolePrefix + role));
}
return authorities;
}
}
In your spring security configuration change the DefaultLdapAuthoritiesPopulator
to your new implementation.
An additional property can set the AllAuthorityFilter
which filters which groups will be returned.
You may prefer your implementation to just retrieve the String
based role names instead of the GrantedAuthority
instances.