Spring Data-LDAP: Part 2
Check out this short tutorial on implementing Spring Security with LDAP information.
Join the DZone community and get the full member experience.
Join For FreeNow, since we have plugged in the LDAP information, it is time to stitch it with Spring Security. The easiest thing to do is:
@Configuration
@EnableWebSecurity(debug = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
@Autowired
private LdapContextSource ldapContextSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().antMatchers("/users","/").permitAll()
.anyRequest().authenticated().and().csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication().contextSource(ldapContextSource)
.userSearchBase("ou=users")
.groupSearchBase("ou=groups")
.groupSearchFilter("member={0}")
.userDnPatterns("ou=users,dc=example,dc=com")
.userSearchFilter("uid={0}");
}
}
I have already added the ldapContextInformation
in the ApacheDSConfiguration
class.
@Bean
LdapTemplate ldapTemplate(ContextSource contextSource) {
return new LdapTemplate(contextSource);
}
After weaving this together, I exposed a new method in the controller:
@ResponseBody
@PostMapping("/protected")
public String protectedMethod(HttpServletRequest request) {
logger.debug(" Requested: " + request.getRequestURI() + " : " + request.getUserPrincipal().getName() + " : " + context.getApplicationName());
return "Method Protected";
}
Additionally, I am ready to fire my application with a post method that has been protected by the backed LDAP (Apache DS).
POST /events/protected HTTP/1.1
> Host: localhost:8082
> Authorization: Basic c3NoYXJtYTpmaXJld2FsbA==
> User-Agent: insomnia/6.3.2
> Cookie: JSESSIONID=A049DCE901E82092A38867FA67A773A9
> Accept: */*
Spring Framework
Opinions expressed by DZone contributors are their own.
Comments