packageLdapTest;importjava.util.Hashtable;importjavax.naming.Context;importjavax.naming.NamingEnumeration;importjavax.naming.NamingException;importjavax.naming.AuthenticationException;importjavax.naming.directory.SearchControls;importjavax.naming.directory.SearchResult;importjavax.naming.ldap.Control;importjavax.naming.ldap.InitialLdapContext;importjavax.naming.ldap.LdapContext;public classAuthenticationTest {private String BASE_DN ="dc=statestreet,dc=com";//private DirContext ctx = null;
private LdapContext ctx = null;private Hashtable env = null;private Control[] connCtls = null;private voidLdapConnect(){
env= newHashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL,");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL,"cn=Manager,dc=statestreet,dc=com");
env.put(Context.SECURITY_CREDENTIALS,"****"); //自己填入
try{
ctx= newInitialLdapContext(env,connCtls);//ctx = new InitialDirContext(env);
System.out.println("Login Ldap Server Successful...");
}catch(AuthenticationException e){
System.out.println("Login Ldap Server Failed...");
e.printStackTrace();
}catch(Exception e){
System.out.println("Login Ldap Server Wrong...\n "+e.toString());
}
}privateString getUserDN(String userid){
String userDN="";try{
SearchControls constraints= newSearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration en= ctx.search("","uid="+userid,constraints);if(en == null){
System.out.println("Have NO such user!");
}if(!en.hasMoreElements()){
System.out.println("Have NO such user!");
}while (en != null &&en.hasMoreElements()){
Object obj=en.nextElement();if(obj instanceofSearchResult){
SearchResult si=(SearchResult) obj;
userDN+=si.getName();
userDN+= "," +BASE_DN;
}else{
System.out.println(obj);
}
}
}catch(Exception e){
System.out.println("Exception in search user DN : "+e.toString());
}returnuserDN;
}public booleanAuthenricate(String ID,String pwd){
LdapConnect();boolean valide = false;
String userDN=getUserDN(ID);if(userDN=="")returnvalide;try{
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL,userDN);
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS,pwd);
ctx.reconnect(connCtls);
System.out.println(userDN+ " is authenticated! ");
valide= true;
}catch(AuthenticationException e) {
System.out.println(userDN+ " is NOT authenticated! ");
valide= false;
}catch(NamingException e) {
System.out.println(userDN+ " is NOT authenticated! ");
valide= false;
}
LdapDisconnect();returnvalide;
}private voidLdapDisconnect(){if (ctx != null) {try{
ctx.close();
}catch(NamingException e) {
e.printStackTrace();
}
}
}
}