Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing ldap connection

I want to validate user entered ldap settings. On settings page user enters ldap url, manager dn and password. I have a 'Test settings' button on this page so that user can quickly verify the ldap connection. How to do this easily and quickly?

Our application using spring security and in the process of adding ldap authentication to it. I am kind of new to java and ldap, so pointing me to right direction is greatly appreciated.

Thanks.

like image 511
user1366786 Avatar asked Jan 03 '13 20:01

user1366786


1 Answers

Based on the information given it is hard to tell what you know and what you don't know yet. So, I suggest you follow this helpful tutorial at java.net LdapTemplate: LDAP Programming in Java Made Simple and skip the chapters not relevant to you (it's from 2006 but still ok). Spring LDAP referenced in the article is at version 1.3.1 by now.

If you want to go without Spring LDAP for now you can use the following traditional code:

Map<String, String> env = new HashMap<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389/dc=jayway,dc=se");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "uid="+ username +",ou=system"); // replace with user DN
env.put(Context.SECURITY_CREDENTIALS, password);

DirContext ctx;
try {
   ctx = new InitialDirContext(env);
} catch (NamingException e) {
   // handle
}
try {
   SearchControls controls = new SearchControls();
   controls.setSearchScope( SearchControls.SUBTREE_SCOPE);
   ctx.search( "", "(objectclass=person)", controls);
   // no need to process the results
} catch (NameNotFoundException e) {
   // The base context was not found.
   // Just clean up and exit.
} catch (NamingException e) {
   // exception handling
} finally {
   // close ctx or do Java 7 try-with-resources http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
}
like image 64
Marcel Stör Avatar answered Sep 30 '22 11:09

Marcel Stör