Skip to content
Advertisement

Ldap AD Authentication in Spring Security

I have a login page in my application where I want to validate the entered username/password against Ldap AD. I am thinking of creating a bind and get a context. If bind is successful that means user is authenticated. In Java I have achieved it like this:

JavaScript

Above code is perfectly working for me. I want to implement the same in spring boot application using spring security. I have tried multiple suggested ways but getting some error every time.

Here I want to authenticate the enter username/password for which I think context binding is enough so not require to search that user again using something like “sAMAccountName={0}” please correct me if I am wrong.


Update

while trying below code, I can see in the logs that it fetches the user details but in the last giving some error:

JavaScript

Error Logs:

JavaScript

enter image description here

Can someone please guide me to migrate this plain java code to spring security.

Regards

Advertisement

Answer

We can see in the trace logs the following message :

JavaScript

The documentation says :

After authenticating the user successfully, the LdapAuthenticationProvider will attempt to load a set of authorities for the user by calling the configured LdapAuthoritiesPopulator.

The default implementation is trying to load the authorities by searching the directory for groups the user is a member of, but is failing to do so because you did not specify the group search base.

JavaScript

Usually, such groups are referenced under an ou=Roles component in the directory tree. For example, given the user search base defined in the “working” code : ou=roles,ou=in,dc=global,dc=company,dc=org, but a larger base (with only dc‘s) should be fine to start with.

It is worth noting that you can set a global base directly in the ldap url, and define relative dn for parameters where a dn is expected (with a valid global base set, leaving groupSearchBase empty wouldn’t throw an error), you could have for example :

JavaScript

with :

JavaScript

Also, note that you don’t need userDnPatterns() when using userSearchFilter(), use either one or the other.

@see Spring Security documentation : Loading Authorities

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement