Home » Java » Enterprise Java » Integrating Active Directory from Java

About Daniel Shaya

Daniel Shaya
Daniel has been programming in Java since it was in beta. Working predominantly in the finance industry he has created real time trading and margin risk applications. He is currently a director at OpenHFT where we are building next generation Java low latency products.

Integrating Active Directory from Java

Firstly you will need to setup Active Directory so that you can run and test your code.

If (like me) you don’t have a machine with Windows Server no worries, this is how you can set up Active Directory even on Mac OSX.

The first thing you want to do is set up a user a in AD.  Make sure that when you set up the user he doesn’t have to change his password on the first login or you will get an LDAP error from your Java code.
 
 
 
Screen Shot 2015-06-12 at 15.17.16
Clearly you can change your code to prompt a password change but just something to be aware of.

Also create a couple of groups for your user and add them to their profile.

In the code below there is just one method, authenticate. It that takes as parameters a user, password and domain and returns a list of groups of which the user is a member. If the user does not exist or there is a problem with the password an exception is thrown.

package util;
 
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.text.MessageFormat;
import java.util.*;
 
public class ADConnect {
    private static final String MEMBER_OF = "memberOf";
 
    public static List<String> authenticate(String user,
                                            String securityToken,
                                            String domain) throws NamingException {
 
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "LDAP://" + domain);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, user + "@" + domain);
        env.put(Context.SECURITY_CREDENTIALS, securityToken);
 
        InitialDirContext ctx = new InitialDirContext(env);
 
        String[] dcParts = domain.split("\\.");
        String domainSearch = "";
        for (String dcPart : dcParts) {
            domainSearch += "DC=" + dcPart + ",";
        }
        domainSearch = domainSearch.substring(0, domainSearch.length() - 1);
 
        // Create the search controls
        SearchControls searchCtls = new SearchControls();
        String[] attributes = new String[]{MEMBER_OF};
        searchCtls.setReturningAttributes(attributes);
 
        // Specify the search scope
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
 
        // Search for objects using the filter
        NamingEnumeration result = ctx.search(domainSearch,
                MessageFormat.format("(SAMAccountName={0})", user), searchCtls);
 
        //Get the first result
        SearchResult sr = (SearchResult) result.next();
 
        Attribute memberOf = sr.getAttributes().get(MEMBER_OF);
        List<String> memberOfGroups = new ArrayList<>();
        if (memberOf != null) {
            for (Enumeration e1 = memberOf.getAll(); e1.hasMoreElements(); ) {
                memberOfGroups.add(e1.nextElement().toString());
            }
        }
        return memberOfGroups;
    }
 
    public static void main(String[] args) throws NamingException{
        System.out.println(ADConnect.authenticate("user", "password", "domain"));
    }
}

The code is fairly self explanatory and you can use it as a template to experiment with adding different attributes to the search.

Reference: Integrating Active Directory from Java from our JCG partner Daniel Shaya at the Rational Java blog.
(0 rating, 0 votes)
You need to be a registered member to rate this.
1 Comment Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Jay
Jay
4 years ago

Hi Daniel,

Do you know what changes do I have to implement in order to find multiple users, or all users ?

Thank you,