Posted By:
james_deibel
Posted On:
Wednesday, July 11, 2001 02:17 PM
Here's the sample code I use everytime I have to code up an
authentication program through LDAP and JNDI. Just be sure
to set the the o and ou settings properly, as well as the
address of your LDAP server. Furthermore, check to see
what authentication service you use.
static final String LDAPServer = "ldap://domain.com:389";
public static boolean authenticate(String name, String passwd)
{
boolean authorized = false;
if(name.equals("") || passwd.equals(""))
return false;
// prepare new env object
Hashtable env = new Hashtable();
// specify context factory
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFacto
ry");
// Specify host and port to use for directory service
env.put( Context.PROVIDER_URL, LDAPServer );
env.put( Context.SECURITY_AUTHENTICATION, "simple");
String principal = "uid="+name+",ou=Blah, o=something.com";
env.put( Context.SECURITY_PRINCIPAL, principal );
env.put( Context.SECURITY_CREDENTIALS, passwd );
try {
// Create initial context
DirContext ctx = new InitialDirContext( env );
// Close the context when we're done
ctx.close();
authorized = true;
}
catch( Throwable e ) {
authorized = false;
}
return authorized;
}