How to Create JWT Token Using LDAP and Spring Boot Part 1

If you are working in an enterprise infrastructures, chances are that you are using a centralized authentication system, most likely Active Directory or openLDAP. In this blog I’ll explore how to create a REST API using spring boot to authenticate against openLDAP and create a JWT token in return.

Before getting our hand dirty, we need to review the architecture of spring security and the way we want to utilise it, in a REST API endpoint. According to openLDAP, I’ve explained it’s concept briefly before, you can read more about it here. Also I’ll assume that you know how Spring Boot and JWT works.

Spring Security

In this example I will extend the WebSecurityConfigurerAdapter. This class will assist me to intercept security chain of spring security and insert openLDAP authentication adapter in between.

In fact this abstract class provides convenient methods for configuring spring security configuration using HTTPSecurity object.

First of all I injected three different beans as follows :

   private OpenLdapAuthenticationProvider openLdapAuthenticationProvider;
   private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
   private JwtRequestFilter jwtRequestFilter;

Then override the configure(AuthenticationManagerBuilder auth) :

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

This will let us to override default behaviour of spring security authentication. In addition we need to override the configure(HttpSecurity httpSecurity):

    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // We don't need CSRF for this example
                // dont authenticate this particular request
                // all other requests need to be authenticated
                // make sure we use stateless session; session won't be used to
                // store user's state.
                // Add a filter to validate the tokens with every request
                httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

Also For the sake of manually authenticating a user in /api/login we will expose the authenticationManagerBean() :

    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();

After configuring WebSecurityConfig, I’ll provide my customer authentication adapter. This adapter will utilise spring’s LdapTemplate and let us to establish a connection to a LDAP server.

public class OpenLdapAuthenticationProvider implements AuthenticationProvider {

    private LdapContextSource contextSource;

    private LdapTemplate ldapTemplate;

    private void initContext() {
// I use anonymous binding so, no need to provide bind user/pass
        ldapTemplate = new LdapTemplate(contextSource);

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        Filter filter = new EqualsFilter("uid", authentication.getName());
        Boolean authenticate = ldapTemplate.authenticate(LdapUtils.emptyLdapName(), filter.encode(),
        if (authenticate) {
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            UserDetails userDetails = new User(authentication.getName() ,authentication.getCredentials().toString()
            Authentication auth = new UsernamePasswordAuthenticationToken(userDetails,
                    authentication.getCredentials().toString() , grantedAuthorities);
            return auth;

        } else {
            return null;

    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);

Another part that we have to take into consideration is, implementing user login controller. Since we haven’t provided any filter for controlling username and password we ought to implementing it manually as follows :

public class LoginController {

    private AuthenticationManager authenticationManager;

    private JwtTokenUtil jwtTokenUtil;

    private UserService userService;

    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception
        authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
        final User userDetails = userService.loadUserByUsername(authenticationRequest.getUsername());
        final String token = jwtTokenUtil.generateToken(userDetails);
        return ResponseEntity.ok(new JwtResponse(token));

    private void authenticate(String username, String password) throws Exception {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (DisabledException e) {
            throw new Exception("USER_DISABLED", e);
        } catch (BadCredentialsException e) {
            throw new Exception("INVALID_CREDENTIALS", e);

These are the pillars of having a REST API + JWT + LDAP back-end using spring boot.

Now we can test the API using a REST client.

Login Endpoint

After getting the JWT token we can call authorized endpoints

You can find a working source code on my github.

For the next part I’ll make this code more concise.