将Java连接到Active Directory

时间:2013-09-01 09:56:43

标签: java active-directory ldap md5 jndi

我尝试使用我的Java代码连接到Active Directory,但是收到此错误消息:

Début du test Active Directory
Search error: javax.naming.AuthenticationException: [LDAP: error code 49 - 8009030C:
LdapErr: DSID-0C0904DC, comment: AcceptSecurityContext error, data 52e, v1db1

我使用JNDI,DIGEST-MD5身份验证方法,没有加密方法 这是我的代码:

public class TestAD {
    static DirContext ldapContext;
    public static void main (String[] args) throws NamingException
    {
        try
        {
            System.out.println("Début du test Active Directory");

            Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
            ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            ldapEnv.put(Context.PROVIDER_URL,  "ldap://societe.fr:389");
            ldapEnv.put(Context.SECURITY_AUTHENTICATION, "DIGEST-MD5");
            ldapEnv.put("java.naming.security.sasl.realm","myRealm");
            ldapEnv.put("javax.security.sasl.qop", "auth");
            ldapEnv.put("javax.security.sasl.strength","high");
            ldapEnv.put(Context.SECURITY_PRINCIPAL, "dn:cn=administrateur,ou=users,o=societe.fr");
            ldapEnv.put(Context.SECURITY_CREDENTIALS,"myPassword");

            ldapContext = new InitialDirContext(ldapEnv);

            // Create the search controls         
            SearchControls searchCtls = new SearchControls();

            // Specify the attributes to return
            String returnedAtts[]={"sn","givenName", "samAccountName"};
            searchCtls.setReturningAttributes(returnedAtts);

            // Specify the search scope
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            // specify the LDAP search filter
            String searchFilter = "(&(objectClass=user))";

            // Specify the Base for the search
            String searchBase = "dc=societe,dc=fr";
            // initialize counter to total the results
            int totalResults = 0;

            // Search for objects using the filter
            NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls);

            // Loop through the search results
            while (answer.hasMoreElements())
            {
                SearchResult sr = (SearchResult)answer.next();

                totalResults++;

                System.out.println(">>>" + sr.getName());
                Attributes attrs = sr.getAttributes();
                System.out.println(">>>>>>" + attrs.get("samAccountName"));
            }

            System.out.println("Total results: " + totalResults);
            ldapContext.close();
        }
        catch (Exception e)
        {
            System.out.println(" Search error: " + e);
            e.printStackTrace();
            System.exit(-1);
        }
    }
}

P.S .:我可以使用与Apache Directory Studio相同的参数连接到我的Active Directory

0 个答案:

没有答案