Connecting to Active Directory using LDAP

The below code can tell that what we can do with java, .NET guys please don’t mind.

String userName = "username";
String passWord = "password";
String base = "cn=Users,dc=ssc,dc=mycompany,dc=com";

Hashtable env = new Hashtable();

public LDAPCrap() {
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=" + userName + "," + base);
env.put(Context.SECURITY_CREDENTIALS, passWord);


public void isAuth() {
try {
LdapContext authContext = new InitialLdapContext(env, null);

String filter = "(objectclass=*)";
String sbase = "";
SearchControls controls = new SearchControls();
                        UsernamePasswordHandler handler = new UsernamePasswordHandler(user,
LoginContext loginContext = new LoginContext("TEST", handler);

// may be a scope change
DirContext ctxGC = new InitialDirContext(env);
NamingEnumeration answer =, filter, controls);
SearchResult sr = (SearchResult); attrs = sr.getAttributes();
System.out.println(" Naming Context: "
+ attrs.get("defaultNamingContext").get());
System.out.println("Bind Successful");
} catch (AuthenticationException authEx) {
System.out.println("Authentication failed!");
} catch (NamingException namEx) {
System.out.println("ERROR IN BIND: " + namEx);



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s