Saturday, November 30, 2013

LDAP authentication using JAVA

package eclipsepackage;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.
NamingEnumeration;
import javax.naming.NameAlreadyBoundException;
import javax.naming.directory.*;

import java.util.*;

public class test {

     final static String ldapServerName = "LDAP://127.0.0.1:389/DC=martinkabraham,DC=com";
     final static String dc1="martinkabraham";
     final static String rootdn = "OU=Martin";
     final static String rootpass = "password";
     final static String rootContext = "OU=Martin";
     final static String username="martin.abraham";
         
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Properties env = new Properties();
       
        env.put( Context.INITIAL_CONTEXT_FACTORY,
                 "com.sun.jndi.ldap.LdapCtxFactory" );
        env.put(Context.REFERRAL, "follow");
        env.put( Context.PROVIDER_URL, ldapServerName);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put( Context.SECURITY_PRINCIPAL, new String(dc1 + "\\"+username) );
        env.put( Context.SECURITY_CREDENTIALS, rootpass );
       
        DirContext ctx = null;
        NamingEnumeration results = null;
        try {
            ctx = new InitialDirContext(env);
            SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            results = ctx.search("", "(sAMAccountName="+username+")", controls);
            while (results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();
                Attributes attributes = searchResult.getAttributes();
             
                if(attributes.get("cn")!=null)
                {
                    // login here .... user exist
                  System.out.println("SUCCESS");
                }
                else
                {
                     System.out.println("F");
               
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            if (results != null) {
                try {
                    results.close();
                } catch (Exception e) {
                }
            }
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (Exception e) {
                }
            }
        }

       
    }

}

No comments:

Post a Comment