LDAP AD Spring Security authentication fails when domain does not match userPrincipalName ending

LDAP AD Spring Security authentication fails when domain does not match userPrincipalName ending

The problem seems to be that createBindPrincipal() inside ActiveDirectoryLdapAuthenticationProvider checks if the username ends with the domain and if not, it appends it. This results in the username becoming john.doe@bar.com@foo.bar.com

Unfortunately, ActiveDirectoryLdapAuthenticationProvider is final, so cannot override it. The solution we went with is to not pass down the domain, but the rootDN instead (constructed by copying code from ActiveDirectoryLdapAuthenticationProvider)

private AuthResultDto loginAD(LoginDto login) {

    String adDomain = env.getProperty(xxx.api.auth.ad.domain);
    String adUrl = env.getProperty(xxx.api.auth.ad.url);

    ActiveDirectoryLdapAuthenticationProvider provider = 
            new ActiveDirectoryLdapAuthenticationProvider(null, adUrl, rootDnFromDomain(adDomain));
    provider.setConvertSubErrorCodesToExceptions(true);
    provider.setUseAuthenticationRequestCredentials(true);
    provider.setUserDetailsContextMapper(new InetOrgPersonContextMapper());

    Authentication auth = provider
            .authenticate(new UsernamePasswordAuthenticationToken(login.getEmail(), login.getPassword()));

    if (!auth.isAuthenticated())
        throw new CustomMessageException(Invalid Login);
...
}

// copied from ActiveDirectoryLdapAuthenticationProvider
private String rootDnFromDomain(String domain) {
    String[] tokens = StringUtils.tokenizeToStringArray(domain, .);
    StringBuilder root = new StringBuilder();

    for (String token : tokens) {
        if (root.length() > 0) {
            root.append(,);
        }
        root.append(dc=).append(token);
    }

    return root.toString();
}

LDAP AD Spring Security authentication fails when domain does not match userPrincipalName ending

Leave a Reply

Your email address will not be published. Required fields are marked *