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.

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.

How to use CompletableFuture in SpringBoot 2

In Spring Boot there is an annotation @Async to assist developers for developing concurrent applications. But using this feature is quite tricky. In this blog we will see how to use this feature along with CompletableFuture. I assumed you know the drill about CompletableFuture, so I won’t repeat the concept here.

First of all you need to annotate your application class with @EnableAsync, this annotation tells the Spring to look for methods that are annotated with @Async and run them in a separate executor.

public class App {
    public static void main(String[] args) {, args);

If you take a look at Spring Boot example about @Async using CompletableFuture you’ll notice the way they’re using this feature is based on a REST request, in my opinion, I beleive, it’s kinda limited, it doesn’t give you a clue of how to use such feature in other situation. For an instance if you have a long running task what would you do about it?

// Source :
package hello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.CompletableFuture;

public class GitHubLookupService {

    private static final Logger logger = LoggerFactory.getLogger(GitHubLookupService.class);

    private final RestTemplate restTemplate;

    public GitHubLookupService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate =;

    public CompletableFuture<User> findUser(String user) throws InterruptedException {"Looking up " + user);
        String url = String.format("", user);
        User results = restTemplate.getForObject(url, User.class);
        // Artificial delay of 1s for demonstration purposes
        return CompletableFuture.completedFuture(results);


In FindUser(String user), it uses a synthetic delay in the main thread also the main task of this method is fetching data from github using RestTemplate, this class is a “Synchronous client to perform HTTP requests”. How about using a long running task such as calling a network function, like ping a server from your REST endpoint? In that case you need to tailor the CompletableFuture. You can’t simply call following line and carry on.

return CompletableFuture.completedFuture(results);

How to Use CompletableFuture

For using @Async in your code, your method has to return Future or CompletableFuture for more information you can refer to its document. Take a look at following example :

    public CompletableFuture<Boolean> isServerAlive(String ip) {
        CompletableFuture<Boolean> future = new CompletableFuture<Boolean>(){
            public Boolean get() throws InterruptedException, ExecutionException {
                InetAddress address = null;
                try {
                    address = InetAddress.getByName(ip);
                    return address.isReachable(1000);
                } catch (UnknownHostException e) {
                    return false;
                } catch (IOException e) {
                    return false;
        return future;

In this example I override the get() method and return the CompletableFuture without any thread executor, in fact with this method we ask Spring to execute the @Async method in a different thread, but we don’t provide any thread executor, only body of a background-worker will suffice.

download source code from github

P.S : In this example I decided to use a network function inside Spring Boot just for the sake of argument. But it’s better to not to use network functions directly in a REST endpoint. Specially when you expect to get an immediate result out of it. The reason: network functions are blocking which means, if you call this REST endpoint. You’ll have to wait to get the result from the endpoint. It’s highly advised to use other methods such as queue or push method(e.g. websocket) for calling blocking functions.