Translate

Saturday, August 29, 2015

Java - Authenicate against Active Directory

It turns out it's very easy using JNDI to authenticate someone against Active Directory.

/**
 * Authenticate against AD
 * @param username The user name
 * @param password The password
 * @return True if authenticate
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public boolean authenicate(String username, String password){
 boolean bRes = true;
 ResourceBundle rsBun = ResourceBundle.getBundle("LDAP_Res");
 Hashtable env = new Hashtable();
 env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
 //Use the secure connection
 env.put(Context.PROVIDER_URL, rsBun.getString("urls"));
 //Add the domain name if the user name does not contain it
 if (username.indexOf(rsBun.getString("domain")) == -1){
  username = rsBun.getString("domain") + "\\" + username;
 }
 env.put(Context.SECURITY_PRINCIPAL, username); 
 env.put(Context.SECURITY_CREDENTIALS, password); 
 try {
  LdapContext ctx = new InitialLdapContext(env,null);
  ctx.close();
 } catch (NamingException e) {
  bRes = false;
 } 
 return bRes;
}

No comments:

Post a Comment

Thank you for commenting!