Here is a simple Java code to validate user login with Windows Active Directory. Tested with
jldap-4.3.jar
jldap-4.3.jar
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Logger;
import com.novell.ldap.LDAPConnection;
import com.novell.ldap.LDAPConstraints;
import com.novell.ldap.LDAPException;
public class LdapCommand {
public LdapCommand() {
}
public static void main(String [] args) {
if (args.length < 5 || args.length > 6) {
System.out.println("Usage: java -jar ./LdapCommand.jar "
+ " ");
System.out.println("Example: java -jar ./LdapCommand.jar mailer01.ad.yourdomain.com 3 389 @ad.yourdomain.com yourname");
System.exit(0);
}
String password = null;
if (args.length == 6)
password=args[5];
if (password == null || password.trim().equals("")) {
System.out.println("Please enter password:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
password = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your password!");
System.exit(1);
}
}
System.out.println("LdapServer:" + args[0]);
System.out.println("LdapVersion:" + args[1]);
System.out.println("LdapPort:" + args[2]);
System.out.println("LdapDomain:" + args[3]);
System.out.println("LdapUser:" + args[4]);
System.out.println("LdapPassword:*******");
int port=0;
try {
port=new Integer(args[2]);
} catch (Exception e) {
System.out.println("incorrect port");
System.exit(3);
}
int version=0;
try {
version=new Integer(args[1]);
} catch (Exception e) {
System.out.println("incorrect version");
System.exit(3);
}
if (args[3].indexOf("@") == -1) {
System.out.println("Incorrect domain (e.g. @ad.yourdomain.com is the correct domain");
System.exit(2);
}
LDAPConnection conn=null;
try {
conn = new LDAPConnection();
LDAPConstraints ldapConstraints = new LDAPConstraints();
ldapConstraints.setReferralFollowing(true);
conn.setConstraints(ldapConstraints);
System.out.println("Connecting to ldap server");
conn.connect(args[0], port);
System.out.println("Binding with ldap server");
conn.bind(version, args[4] + args[3], password.getBytes());
System.out.println("AD authentication succeeded for user=" + args[4]);
} catch (LDAPException le) {
System.out.println("failed login for user=" + args[4]);
le.printStackTrace();
} catch (Exception e) {
System.out.println("failed login for user=" + args[4]);
e.printStackTrace();
} finally {
try {
conn.disconnect();
} catch (Exception e) {
System.out.println("cannot disconnect ");
e.printStackTrace();
};
}
}
}
No comments:
Post a Comment