Search code examples
javaspring-bootactive-directoryldap

Connect to on Prem Microsoft Active Directory using Java


I'm new to this and am trying to connect to an on Prem Microsoft Active Directory with Java spring boot. the Active Directory is deployed on a remote server and I'm accessing the server using Microsoft Remote Desktop. Is there any way to establish a connection and authenticate the user?

Update:

i'm able to connect to AD but getting a NamingException

    String username = "[email protected]";
    String password = "Yahoo@1234";
    String url = "ldap://100.36.224.125:389/dc=springframework,dc=org";
    String base = "ou=people,dc=example,dc=com";

    Hashtable<String, Object> ldapParams = new Hashtable<String, Object>();
    ldapParams.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    ldapParams.put(Context.PROVIDER_URL, url);
    ldapParams.put(Context.SECURITY_AUTHENTICATION, "simple");
    ldapParams.put(Context.SECURITY_PRINCIPAL, username);
    ldapParams.put(Context.SECURITY_CREDENTIALS, password);

    // Specify SSL
    //ldapParams.put(Context.SECURITY_PROTOCOL, "ssl");

    InitialDirContext ldapCtx = null;



    try {
        ldapCtx = new InitialDirContext(ldapParams);
        System.out.println(ldapCtx);
        if (ldapCtx != null) {
            System.out.println("login success.");

            
            
            String searchFilter = "(cn=itadmin)";

            SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            NamingEnumeration<SearchResult> results = ldapCtx.search(base, searchFilter, controls);

            while (results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();
                Attributes attributes = searchResult.getAttributes();
                Attribute attr = attributes.get("cn");
                String cn = (String) attr.get();
                System.out.println(" Person Common Name = " + cn);
            }
        }
    } catch (AuthenticationException ex) {
        System.out.println("login fail. [err 1]");
        System.err.println(ex);
    } catch (NamingException ex) {
        System.out.println("login fail. [err 2]");
        System.err.println(ex);
    } catch (Exception e) {
        System.out.println("login fail. [err 3]");
        System.err.println(e);
    } finally {
        System.out.println("LDAP Context is " + ldapCtx);
    }

Solution

  • As you are using spring already you will probably want to follow the spring guide to authenticating with LDAP.

    What you should know is that Active Directory is a LDAP server as well.

    The biggest problem with LDAP is to figure out what all the parameters should be.