Monday, March 2, 2009

Portlets accessing LDAP

LDAP authenticator is a cornerstone in any architecture that aims to have a centralized point of authentication. The WebSphere Portal allows you to configure your repository, pointing to an LDAP authentication in native.

However there are situations where you need to access LDAP directly through a portlet. There are several libraries on the Internet with suggestions of connections, but the most recommended for the WebSphere environment is to use the very mechanism provided by the application server jndi.

Here is a sample code of how to access it.

/ * Indicates the LDAP properties
Hashtable Hashtable env = new Hashtable env = new Hashtable (); ();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put (Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389"); env.put (Context.PROVIDER_URL, "ldap: / / localhost: 389");
env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put (Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=Manager,dc=ibm,dc=com"); env.put (Context.SECURITY_PRINCIPAL, "cn = Manager, dc = ibm, dc = com");
env.put(Context.SECURITY_CREDENTIALS, "password"); env.put (Context.SECURITY_CREDENTIALS, "password");

try { try (
// Lets send controls in the LDAP search. Exemplo: SORT Example: SORT
Control[] connectionControls = null; Control [] connectionControls = null;

LdapContext ctx = new InitialLdapContext(env, connectionControls); LdapContext ctx = new InitialLdapContext (env, connectionControls);
Attributes attrs = ctx.getAttributes("uid=alexbc,ou=users,dc=ibm,dc=com"); Attributes attrs = ctx.getAttributes ( "uid = alexbc, ou = users, dc = ibm, dc = com");

System.out.println("sn: " + attrs.get("userPassword").get()); System.out.println ( "sn:" + attrs.get ( "userPassword"). Get ());
System.out.println("sn: " + attrs.get("cn").get()); System.out.println ( "sn:" + attrs.get ( "cn"). Get ());

} catch (NameNotFoundException nnf) { ) Catch (NameNotFoundException nnf) (
System.out.println("Elemento nao encontrado"); System.out.println ( "Element not found");

} catch (NamingException e) { ) Catch (NamingException e) (
System.err.println("Erro no acesso LDAP: " + e); System.err.println ( "Error in accessing LDAP:" + e);
} )