Skip to content

Instantly share code, notes, and snippets.

@mpilone
Created November 21, 2013 14:38
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save mpilone/7582628 to your computer and use it in GitHub Desktop.
Save mpilone/7582628 to your computer and use it in GitHub Desktop.
A simple example of using Spring LDAP to authenticate a user against Active Directory.
// Setup the LDAP client (normally done via Spring context file).
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl("ldap://adserver.mycompany.com:3268");
contextSource.setBase("DC=AD,DC=MYCOMPANY,DC=COM");
contextSource.setUserDn("readonlyuser@ad.mycompany.com");
contextSource.setPassword("password1");
contextSource.afterPropertiesSet();
LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
ldapTemplate.afterPropertiesSet();
// Perform the authentication.
Filter filter = new EqualsFilter("sAMAccountName", "mpilone");
boolean authed = ldapTemplate.authenticate("OU=CorpUsers",
filter.encode(),
"user-entered-password");
// Display the results.
System.out.println("Authenticated: " + authed);
@selperin
Copy link

Hi, thanks for the very good example. Question - do you have a code which uses paged query to authenticate the user. For big LDAPs ldapTemplate.authenticate() method fails due to LDAP query limitation - 5000 entries max
Thanks, Sam

@kcotzen
Copy link

kcotzen commented Sep 5, 2019

Thank's a lot

@sarrit
Copy link

sarrit commented Oct 10, 2019

I use the above code for ldap authentication,But im getting the javax.naming.nopermissionexception: [ldap error code 50 anonymous access] remaining name "dc=test,com=ex".but at the same time im able to search the user and get their respective attributes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment