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) :

 @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(openLdapAuthenticationProvider);
    }

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

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // We don't need CSRF for this example
        httpSecurity
                .csrf().disable()
                .headers()
                .frameOptions()
                .deny()
                .and()
                // dont authenticate this particular request
                .authorizeRequests().antMatchers("/api/login").permitAll().
                // all other requests need to be authenticated
                antMatchers("/api/**").authenticated().and().
                // make sure we use stateless session; session won't be used to
                // store user's state.
                exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
                // 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() :

  @Bean
    @Override
    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.

@Component
public class OpenLdapAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private LdapContextSource contextSource;

    private LdapTemplate ldapTemplate;

    @PostConstruct
    private void initContext() {
        contextSource.setUrl("ldap://1.1.1.1:389/ou=users,dc=www,dc=devcrutch,dc=com");
// I use anonymous binding so, no need to provide bind user/pass
        contextSource.setAnonymousReadOnly(true);
        contextSource.setUserDn("ou=users,");
        contextSource.afterPropertiesSet();
        ldapTemplate = new LdapTemplate(contextSource);
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

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

        } else {
            return null;
        }
    }

    @Override
    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 :

@RestController
@RequestMapping("/api/login")
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserService userService;



    @PostMapping
    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 Authenticate Against openLDAP Without Knowing DN Using java

In fact you can’t do it without knowing DN! There is an anonymous access in openLDAP which is enabled by default. The anonymous access let one to query(search filter) openLDAP without knowing bind username/password.

Run following command on your openLDAP server :

ldapwhoami -H ldap:// -x

If you get “anonymous” as result you are all set and your openLDAP is supporting anonymous query, otherwise this blog is not the one you are looking for!

So What’s the Deal?

Assume you know UID of the user in ldap directory but not his DN and assume the root directory hierarchy is : dc=devcrutch,dc=com . How do you want to get CN and then DN of such user in LDAP just by using UID? you might think of such query to get data out of openLDAP

uid=USERNAME,dc=devcrutch,dc=com

If you run this query, it’ll get you to nowhere.

Here Comes the Anonymous Query

First of all you have to query the whole directory for finding such user. You have to create a query similar to following:

(&(objectClass=*)(uid=USERNAME))

This query will search the entire Directory Information Tree (DIT) for such user name.

ldapsearch -x -h 127.0.0.1 -b dc=devcrutch,dc=com "(&(objectClass=*)(uid=USERNAME))"

With such query you can get the DN. Using DN and password you can authenticate against LDAP.

Well this was the idea, applying a search filter using USERNAME via anonymous identity then find the DN and finally login using the retrieved DN.

Time for Some java

Now we have the rough idea it’s time to implement it in java. For finding DN you need to query the entire LDAP directory (note: in real world searching the entire directory is not a good idea, you have to narrow your query, otherwise your query might consume all the server’s resources)

private String findDN(String user) throws Exception {
    DirContext ctx = getContext();
    String dn = null;
    String filter = "(&(objectClass=*)(uid=" + user + "))";
    NamingEnumeration answer = ctx.search("", filter, getSimpleSearchControls());
    if (answer.hasMore()) {
        SearchResult result = (SearchResult) answer.next();
        dn = result.getNameInNamespace();
    }
    answer.close();
    return dn;
}

Then after finding the correct DN you can bind your username and password

public DirContext bind(String username, String password) throws Exception {
        DirContext dirContext;
        Hashtable<String, String> env = new Hashtable<String, String>();
        String dn = findDN(username);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, dn);
        env.put(Context.SECURITY_CREDENTIALS, password);
        try {
            dirContext = getContext(env);
        } catch (javax.naming.AuthenticationException e) {
            throw new Exception(e);
        }
        return dirContext;
}

That’s it.

You can find a working source code on my github


Installing openLDAP and Making it Replicable

OpenLDAP installation is fairly straight-forward and doesn’t have any caveats, but making it replicable has ambiguity. We will start with installing openLDAP. I will use following configs :

  • ubuntu 16.04 server
  • openLDAP 2.4.x
  • phpLDAPadmin

Installing openLDAP :

First thing first, update your ubuntu box :

sudo apt-get update

Install openLDAP :

sudo apt-get install slapd ldap-utils

During installation process you will prompted to enter administrator password. After installing the ldap server you need to configure it :

sudo dpkg-reconfigure slapd

You will see a basic gui with couple of prompts of how to configuring your openLDAP here is my config:

  • Omit openLDAP Server Configuration : No
  • DNS Domain : your domain in my case, lab.devcrutch.com
  • Organization Name : whatever you fancy, lab
  • Database : MDB (It’s an in-memory database based on BerkeleyDB. In case you were curious)
  • Remove Database when openLDAP is Removed : No
  • Move Old Database : Yes
  • Allow LDAP2 : No

That’s it, if you ever want to check status of your openLDAP :

ldapwhoami -H ldap:// -W -D "cn=admin,dc=lab,dc=devcrutch,dc=com"

This command will prompt you to enter your password and if you enter it correctly you will get following response :

dn:cn=admin,dc=lab,dc=devcrutch,dc=com

You are all set to use openLDAP. Now let’s add an user for replication purposes inside provider (master) node. The replication user only needs to have a password and an OU, run following commands to add repl user with only a password

dn: cn=repl,dc=lab,dc=devcrutch,dc=com
objectClass: simpleSecurityObject
objectClass: organizationalRole
cn: repl
userPassword: {SSHA}Px1UjD+3EMII0g+JZBdZkdO6lhZt4j4k
#password is abc123

Save the above file in an LDIF file and run following command. I will call this file add_repl.ldif

ldapadd -Y EXTERNAL -H ldapi:// -f add_repl.ldif

This user needs to have a privilege to only read couple of items from directory, the most important items to read, is userPassword, cn, uid and shadowLastChange. But before granting such access there is an issue with openLDAP’s configs that shipped by Ubuntu 16.04. It is best to remove those configs using following command :

#Run ldapsearch -Y EXTERNAL -H ldapi:// -b "cn=config"

#Not approapriate configs for making your openLDAP replicable
olcAccess: {0}to attrs=userPassword by self write by anonymous auth by * none
olcAccess: {1}to attrs=shadowLastChange by self write by * read
olcAccess: {2}to * by * read

For deleting them run:

ldapmodify -Y EXTERNAL -H ldapi://

In the prompt write following lines one by one (this way you will delete them step by step for the sake of not getting any error)

dn: olcDatabase={1}mdb,cn=config 
changetype: modify
delete: olcAccess
olcAccess: {0}to attrs=userPassword by self write by anonymous auth by * none
#press enter
dn: olcDatabase={1}mdb,cn=config 
changetype: modify
delete: olcAccess
olcAccess: {0}to attrs=shadowLastChange by self write by * read
#press enter
dn: olcDatabase={1}mdb,cn=config 
changetype: modify
delete: olcAccess
olcAccess: {0}to * by * read
#Press ctrl-d at the end

And add following configs :

#Execute ldapmodify -Y EXTERNAL -H ldapi://
#Then write these configs in it, at end press ctrl-d
dn: olcDatabase={1}mdb,cn=config
changetype: modify
add: olcAccess
olcAccess: {0}to attrs=userPassword,shadowLastChange by self write by anonymous auth by dn="cn=admin,dc=lab,dc=devcrutch,dc=com" write by dn="cn=repl,dc=lab,dc=devcrutch,dc=com" read by * none
#press enter
dn: olcDatabase={1}mdb,cn=config
changetype: modify
add: olcAccess
olcAccess: {1}to dn.base="" by * read
#press enter
dn: olcDatabase={1}mdb,cn=config
changetype: modify
add: olcAccess
olcAccess: {2}to * by self write by dn="cn=admin,dc=lab,dc=devcrutch,dc=com" write by * read

Now your provider is ready. We will go to consumer server. First of all install openLDAP using mentioned configs, it should be the same as the master. At the end add following configs into your consumer’s openLDAP :

#run ldapmodify -Y EXTERNAL -H ldapi://
dn: olcDatabase={1}hdb,cn=config
changetype: modify
add: olcDbIndex
olcDbIndex: entryUUID eq
#press enter
dn: olcDatabase={1}hdb,cn=config
changetype: modify
add: olcDbIndex
olcDbIndex: entryCSN eq
#press enter
dn: olcDatabase={1}hdb,cn=config
changetype: modify
add: olcDbIndex
olcDbIndex: ou eq
#press enter
dn: olcDatabase={1}hdb,cn=config
changetype: modify
add: olcDbIndex
olcDbIndex: uid eq
#press enter
dn: olcDatabase={1}hdb,cn=config
changetype: modify
add: olcDbIndex
olcDbIndex: cn eq
#press enter
dn: olcDatabase={1}hdb,cn=config
changetype: modify
add: olcDbIndex
olcDbIndex: dc eq
#press enter
dn: olcDatabase={1}hdb,cn=config
changetype: modify
add: olcSyncrepl
olcSyncrepl: rid=001 provider="ldap://YOUR_MASTER_IP_ADDRESS:389/" type=refreshAndPersist retry="60 30 300 +" searchbase="dc=lab,dc=devcrutch,dc=com" bindmethod=simple binddn="cn=repl,dc=lab,dc=devcrutch,dc=com" credentials="abc123"

The reason I separate configs is because of stupidity level of ldap tools. If you happen to have one of these configs inside your openLDAP previously, the ldapmodify nags about it and will kick you out without knowing which config is saved and which one isn’t, so the best way for me was saving them sequentially.

Reason for having another user rather the “cn=admin” was because of  security, if you take a closer look at the latter config you will see that you have to add your password as a plain text. So it’s best to not to reveal your admin’s password. The repl user is a readonly user.

At the end you can install phpOpenLDAP in provider and consumer :

sudo apt-get install phpldapadmin

Edit below config :

sudo vim /etc/phpldapadmin/config.php

Change the following :

Find the line contains

$servers->setValue('server','base',array('dc=example,dc=com'));

Change it to

$servers->setValue('server','base',array('dc=lab,dc=devcrutch,dc=com'));

And another line contains

$servers->setValue('login','bind_id','cn=example,dc=com');

Change it to

$servers->setValue('login','bind_id','cn=admin,dc=lab,dc=devcrutch,dc=com');

Note: In this tutorial I’ve tried to create a replication server, replication doesn’t mean you have availability, which means if your master(provider) server is down then your client querys the slave(consumer) server. Replication means consistency not availability. If you happen to want availability you need to config openLDAP in multi-master mode.