Skip to main content

Authenticating Spring Boot based application against secure LDAP/AD server


Authenticating against an Active Directory setup is quite common in organizations using Spring Boot / Spring Security can be a pain if you don't know exactly the requirements. I needed to add auth in my web app and secure some but not all endpoints of the application.

My story was,

  • I needed Spring security to authenticate against my company LDAP server which uses Active Directory
  • I started by using the standard LDAP guide such as this which are all over the Internet, https://spring.io/guides/gs/authenticating-ldap/ and was able to setup the basic framework
  • However, only test level LDAP auth was working for me, when I tried to auth against the company LDAP secure server, I had to resolve a few issues
  • After 1 week and working with several devs at the company, I finally found why it was not working and the fix was easy

Since I spent a week or so resolving this, I wanted to write this up in case someone finds this useful.

Here is what I did (it was easy until the fourth step from online material, but not the fourth step, so read carefully!)

Setup Spring boot application with Spring Security enabled

This is pretty easy just follow along the Spring security guide at this page and you are all set : https://spring.io/guides/gs/authenticating-ldap/

At this point, my WebSecurityConfig configuration class looked similar to this and only supported embedded LDAP testing server provided by Spring security


configurations/WebSecurityConfig.java

package com.xyz.configurations;

@Log
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        log.info("Handling http request " + http.toString());
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin().and()
                .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/");
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        log.info("Handling ldap request " + auth.toString());

        
            // embedded ldap used during testing
            auth.ldapAuthentication().userDnPatterns("uid={0},ou=people")
                    .groupSearchBase("ou=groups")
                    .contextSource()
                    .url("ldap://localhost:8389/dc=springframework,dc=org")
                    .and()
                    .passwordCompare()
                    .passwordEncoder(new LdapShaPasswordEncoder())
                    .passwordAttribute("userPassword");
        
    }
}




application.properties

spring.ldap.embedded.base-dn=dc=springframework,dc=org

spring.ldap.embedded.port=8389

spring.ldap.embedded.ldif=classpath:ldapserver-test.ldif


src/main/resources/ldapserver-test.ldif

dn: uid=ben,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Ben Alex
sn: Alex
uid: ben
userPassword: {SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ=

Test against local embedded LDAP to ensure config/code logic is correct

I am not describing here how your frontend works, but based on above config, once you configure your login page, you will see a login screen (default login page by spring security)

When you login, enter 'ben' and 'benspassword' and that should authenticate.

So far so good, this is not a big issue for most users. And this is insecure method. So now for the tricky stuff for which I actually wrote this article.

Now for the secure AD auth: Add support to authenticate against secure LDAP server

Step 1 here is to understand your company's auth requirements. In my case, I eventually found out they use Active Directory (which actually matters here), and they wanted me to do secure auth not just simple auth (which is easier of course). Please never do simple auth for any serious application.

So to do secure auth, there are these steps:

  1. Generate a keystore file containing information about your ldap server
  2. Register this keystore file in your application
  3. Configure WebSecurityConfig configuration above to use AD auth instead of regular LDAP (like shown above)

Generating key looks like this (contact your sysadmin for this step of course). Also refer to to https://github.com/escline/InstallCert for how to do this.

If done correctly you get a keystore.jks file properly setup for your server. Save/commit that file into your project (I use src/main/resources/keystore.jks)

Now, tell your application to use this keystore file. One way to do that is to pass -D args when starting app. My spring boot app is generally started like this to secure auth:

java -Dldap.key-store=./src/main/resources/keystore.jks
you can of course also use profiles to set this value or however you want to locate this file. Regardless, the point is that we locate this file and next is to ask the jdk security subsystem to use this keystore.

Now I updated WebSecurityConfig to check for presence of such a variable and then enable secure-auth, otherwise it will still do the embedded server LDAP


application.properties

    ldap.key-store=./src/main/resources/keystore.jks


configurations/WebSecurityConfig.java

package com.xyz.configurations;

@Value("${ldap.key-store}")
private String ldapKeyStoreFile;

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        log.info("Handling ldap request " + auth.toString());

        // AD/LDAP auth is enabled?
        if (!StringUtils.isEmpty(ldapKeyStoreFile)) {

            String keyStoreFile = new File(ldapKeyStoreFile).getAbsolutePath();
            String keyStorePwd = "whateverpwdyouusedtocreatekeystore"; 
            // also get this from env to be a bit safer

            System.setProperty("javax.net.ssl.trustStore", keyStoreFile);
            System.setProperty("javax.net.ssl.trustStorePassword", keyStorePWD);
            System.setProperty("javax.net.ssl.keyStore", keyStoreFile);
            System.setProperty("javax.net.ssl.keyStorePassword", keyStorePWD);

            auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider())
                    .userDetailsService(userDetailsService());

        } else {
            // embedded ldap used during testing
            auth.ldapAuthentication().userDnPatterns("uid={0},ou=people")
                    .groupSearchBase("ou=groups")
                    .contextSource()
                    .url("ldap://localhost:8389/dc=springframework,dc=org")
                    .and()
                    .passwordCompare()
                    .passwordEncoder(new LdapShaPasswordEncoder())
                    .passwordAttribute("userPassword");
        }
    }

    public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
        /**
         * active-directory:
         ldap:
         url: ldaps://serveraddress/used/during/keystore/creation
         domain: yourdomain.com
         rootDn: dc=xyz, dc=sds
         */
        ActiveDirectoryLdapAuthenticationProvider provider =
                new ActiveDirectoryLdapAuthenticationProvider("zyz.com",
                        "ldaps://secureServeraddress", "dc=xyz, dc=sds");
        provider.setConvertSubErrorCodesToExceptions(true);
        provider.setUseAuthenticationRequestCredentials(true);
        return provider;
    }

}




Notice that the ldap server address is a secure one with "ldaps"
Notice that we are using a different auth mechanism

authenticationProvider

instead of

ldapAuthentication()

for the secure case.

Now this should work. Yes there are a lot of moving parts and anything can be incorrectly setup. So it's important to work with your sysadmin to get the last steps correct.

Hope this saves you a bunch of pain in the A...

Next, I will write other pieces about how you can leverage the auth information in your UIs, controllers, configure specific endpoints to be secured vs nonsecure etc.

Enjoy!






Comments

Popular posts from this blog

Unit testing code that uses environment variables and system properties with fakes

I did not exactly learn this today, but I am sharing it as I have found it extremely useful when unit testing code that depends on environment or system property settings. While I am using Java as an example, the general concepts apply any where. Problem : You have a piece of code you are unit testing that uses settings from env variables or system properties passed to the VM (System.getProperty), but you don't want the tests to be affected by the 'real' environment or system properties in the VM. So, your unit tests should not get different results or fail when the real environment changes. Solution : There are several. But the most straightforward is to use a mocking library to mock out the environment or fake it out, whatever your prefer. You can create a fake using a library like EasyMock, PowerMock etc. This I won't discuss in this post, since there are numerous articles for that. Or you can write a simple class that acts as a proxy, using the proxy pattern

Using custom conditional logic to enable/disable Spring components

If you have a Spring component and you don't want it to load, you can use Spring's predefined conditionals as much as possible. For example, @Component   @ConditionalOnNotWebApplication   public class SchedulerEntryPoint implements ApplicationRunner { ...  } This will not load your component when running in non web application mode. Such as you may want to start the application but without any of the web framework using SpringApplicationBuilder. But sometimes you want to use custom conditions. It's pretty easy to do so, just use something like this @Component @Conditional (SchedulerCheck. class ) public class SchedulerEntryPoint implements ApplicationRunner { public static class SchedulerCheck implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return System. getProperty ( "scheduler" ) !=