spring-security-ldap
Intro to Spring Security LDAP
Further reading:
Spring LDAP Overview
Learn how to use the Spring LDAP APIs to authenticate and search for users, as well as to create and modify users in the directory server.
2. Maven Dependency
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
</dependency>
<dependency>
<groupId>org.apache.directory.server</groupId>
<artifactId>apacheds-server-jndi</artifactId>
<version>1.5.5</version>
</dependency>
Note: We used ApacheDS as our LDAP server which is an extensible and embeddable directory server.
3. Java Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication()
.userSearchBase("ou=people")
.userSearchFilter("(uid={0})")
.groupSearchBase("ou=groups")
.groupSearchFilter("member={0}")
.contextSource()
.root("dc=baeldung,dc=com")
.ldif("classpath:users.ldif");
}
}
This is of course only the LDAP relevant part of the config – the full Java configuration can be found here.
4. XML Configuration
<authentication-manager>
<ldap-authentication-provider
user-search-base="ou=people"
user-search-filter="(uid={0})"
group-search-base="ou=groups"
group-search-filter="(member={0})">
</ldap-authentication-provider>
</authentication-manager>
<ldap-server root="dc=baeldung,dc=com" ldif="users.ldif"/>
Again, this is just part of the configuration – the part that is relevant to LDAP; the full XML config can be found here.
5. LDAP Data Interchange Format
LDAP data can be represented using the LDAP Data Interchange Format (LDIF) – here’s an example of our user data:
dn: ou=groups,dc=baeldung,dc=com
objectclass: top
objectclass: organizationalUnit
ou: groups
dn: ou=people,dc=baeldung,dc=com
objectclass: top
objectclass: organizationalUnit
ou: people
dn: uid=baeldung,ou=people,dc=baeldung,dc=com
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Jim Beam
sn: Beam
uid: baeldung
userPassword: password
dn: cn=admin,ou=groups,dc=baeldung,dc=com
objectclass: top
objectclass: groupOfNames
cn: admin
member: uid=baeldung,ou=people,dc=baeldung,dc=com
dn: cn=user,ou=groups,dc=baeldung,dc=com
objectclass: top
objectclass: groupOfNames
cn: user
member: uid=baeldung,ou=people,dc=baeldung,dc=com
6. The Application
@Controller
public class MyController {
@RequestMapping("/secure")
public String secure(Map<String, Object> model, Principal principal) {
model.put("title", "SECURE AREA");
model.put("message", "Only Authorized Users Can See This Page");
return "home";
}
}
7. Conclusion
In this quick guide to Spring Security with LDAP, we learned how to provision a basic system with LDIF and configure the security of that system.
The full implementation of this tutorial can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.