简体   繁体   中英

Authenticate via Active Directory using LDAP, Java Play Framework

I'm trying to authenticate via Windows Active Directory using LDAP. I have a LDAPContext class that sets up the context and an authenticate method that should find the email in the AD.

This is my LDAPContext class:

public class LDAPContext extends InitialDirContext {

    Hashtable<String, String> env = new Hashtable<String, String>();


    public LDAPContext(String email, String password) throws NamingException
    {
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://myintranet.com");
        env.put(Context.SECURITY_AUTHENTICATION,"simple");
        env.put(Context.SECURITY_PRINCIPAL,"mail="+email+"\""); // specify the username
        env.put(Context.SECURITY_CREDENTIALS,password);
        DirContext ctx = new InitialDirContext(env);
    }
}

And this is my authenticate method:

public static User authenticate(final String email, final String password){
    try { 
        LDAPContext adContext = new LDAPContext(email, password);
        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute("mail", email));
        NamingEnumeration<SearchResult> en = adContext.search("", matchAttrs);

       while(en.hasMore()) {
           System.out.println("Found email!!!");
       }
    } catch(NamingException e) {
        System.out.println("NamingException");
    }
...

I continuously get "NamingException" error. I'm sure the email is in the AD and the specified name of email is "mail". What have I done wrong?

EDIT: This is the specific error I'm getting:

javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1 ]

It means that the credentials are wrong. I've tried to hard-code it, but it still does not work.

The issue is the SECURITY_PRINCIPAL value you're trying to use is not a valid value that you can bind on. It's only possible to bind with a username, not the attributes associated with a user.

Active directory allows you to bind on either username@domain or the user accounts full Distinguishing Name. The DN value is often something like...

cn=username,cn=Users,dc=abc,dc=mycompany,dc=com

but the actual value depends on your AD configuration.

If you want to find a user by their email address, you'll need to bind using an administrator ID (or some ID that has the ability to search), search for the user with that specific email address, then rebind with their username to authenticate.

Also, not that it changes anything, but in the bind name ( "mail="+email+"\\"" ) you have a closing " but not an opening one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM