如何从InitialLdapContext对象获取连接状态和用户详细信息?

时间:2018-09-06 05:42:03

标签: java ldap

我有一个应用程序,需要根据Active Directory检查用户凭据,并且必须根据连接状态将值分配给statusCode。那是因为稍后我将通过包含stausCode来创建JSON响应。到目前为止,对我而言,唯一可行的方法似乎是根据引发的异常的消息值将值分配给statusCode字段。但是,这样做是违反直觉的,我想知道是否存在一种方法来提取连接状态,并且如果成功连接,则从返回的数据中提取用户详细信息 InitialLdapContext

package archive.util;

    import java.net.InetAddress;
    import java.net.UnknownHostException;
    import java.util.Hashtable;
    import javax.naming.CommunicationException;
    import javax.naming.Context;
    import javax.naming.NamingException;
    import javax.naming.ldap.InitialLdapContext;
    import javax.naming.ldap.LdapContext;

    public class AuthActiveDirectory {

        public static void main(String[] args){
            int statusCode = 1;
            try {
                LdapContext ldpt = getConnection("user", "pass", null, null);
            } catch (NamingException ex) {
                if(ex.getMessage().equals("credentials")) {
                    statusCode = 2;
                }
                else if(ex.getMessage().equals("connection")) {
                    statusCode = 3;
                }
            }


        }


        private static final String CONTEXT_FACTORY_CLASS = "com.sun.jndi.ldap.LdapCtxFactory";

        public static LdapContext getConnection(String username, String password, String domainName, String serverName)throws NamingException {
            if (domainName == null) {
                try {
                    String fqdn = InetAddress.getLocalHost().getCanonicalHostName();
                    System.out.println(fqdn);
                    if (fqdn.split("\\.").length > 1) {
                        domainName = fqdn.substring(fqdn.indexOf(".") + 1);
                    }
                } catch (UnknownHostException localUnknownHostException) {
                }
            }
            if (password != null) {
                password = password.trim();
                if (password.length() == 0) {
                    password = null;
                }
            }

            Hashtable props = new Hashtable();
            String principalName = username + "@" + domainName;
            props.put(Context.SECURITY_PRINCIPAL, principalName);
            if (password != null) {
                props.put(Context.SECURITY_CREDENTIALS, password);
            }
            String ldapURL = "ldap://" + (serverName == null ? domainName : new StringBuilder().append(serverName).append(".").append(domainName).toString()) + '/';
            props.put(Context.INITIAL_CONTEXT_FACTORY, CONTEXT_FACTORY_CLASS);
            props.put(Context.PROVIDER_URL, ldapURL);

            try {
                return new InitialLdapContext(props, null);
            } catch (CommunicationException e) {
                throw new NamingException("connection");
            } catch (NamingException e) {
                throw new NamingException("credentials");
            }
        }
    }

0 个答案:

没有答案