How do a LDAP search/authenticate against this LDAP in Java

前端 未结 3 366
一生所求
一生所求 2020-12-02 05:57

I am playing with LDAP and Java search. Here\'s my LDIF export with a simple organization

version: 1

dn: dc=example,dc=com
objectClass: organization
objectC         


        
3条回答
  •  有刺的猬
    2020-12-02 06:25

    You can also use the following code :

    package com.agileinfotech.bsviewer.ldap;
    
    import java.util.Hashtable;
    import java.util.ResourceBundle;
    
    import javax.naming.Context;
    import javax.naming.NamingException;
    import javax.naming.directory.DirContext;
    import javax.naming.directory.InitialDirContext;
    
    public class LDAPLoginAuthentication {
        public LDAPLoginAuthentication() {
            // TODO Auto-generated constructor
        }
    
        ResourceBundle resBundle = ResourceBundle.getBundle("settings");
    
        @SuppressWarnings("unchecked")
        public String authenticateUser(String username, String password) {
            String strUrl = "success";
            Hashtable env = new Hashtable(11);
            boolean b = false;
            String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
            env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
            env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
            env.put(Context.SECURITY_CREDENTIALS, password);
    
            try {
                // Create initial context
                DirContext ctx = new InitialDirContext(env);
                // Close the context when we're done
                b = true;
                ctx.close();
    
            } catch (NamingException e) {
                b = false;
            } finally {
                if (b) {
                    strUrl = "success";
                } else {
                    strUrl = "failer";
                }
            }
            return strUrl;
        }
    }
    

提交回复
热议问题