首页 > 解决方案 > 与管理员绑定后使用 LDAP 对用户进行身份验证?

问题描述

我一直在尝试构建一个在 Tomcat 9 上运行的 Web 应用程序,它通过 LDAP 服务器对用户进行身份验证。请在下面查看我的代码:

        String username = request.getParameter("uname");
        String password = request.getParameter("password");
        
        String base = "DC=xsoltns,DC=y";
        String dn = "CN=Admin,CN=Users," + base;
        String ldap_url = "ldap://address:389";
        
        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, ("com.sun.jndi.ldap.LdapCtxFactory"));
        props.put(Context.PROVIDER_URL, ldap_url);
        props.put(Context.SECURITY_PRINCIPAL, dn);
        props.put(Context.SECURITY_CREDENTIALS, "adminpassword");
        
        try 
        {
            InitialDirContext context = new InitialDirContext(props);
            
            String principle_name = username+"@mydomain.com";
            
            
            SearchControls ctrls = new SearchControls();
            ctrls.setReturningAttributes(new String[] {"givenName", "sn", "memberOf"});
            ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            
            NamingEnumeration<javax.naming.directory.SearchResult> answers = 
                    context.search(base, "(uid="+principle_name+")", ctrls);
            javax.naming.directory.SearchResult result = answers.nextElement();
            String user = result.getNameInNamespace();
            
            try 
            {
                props = new Properties();
                props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
                props.put(Context.PROVIDER_URL, ldap_url);
                props.put(Context.SECURITY_PRINCIPAL, user);
                props.put(Context.SECURITY_CREDENTIALS, password);

                context = new InitialDirContext(props);
                
                //user authenticated
                
            } catch (Exception e)
            {
                //error with user auth
            }
                    
            
        } catch (Exception e) 
        {
            //error with admin auth
            
        }

该程序使用管理员帐户成功绑定,但未根据提供的用户名定位用户。在构建此应用程序时,我一直在使用以前的答案LDAP Authentication using Java作为参考。我的目标是提供用户名,然后在目录中搜索用户的全名(作为 CN 提供二级身份验证)。经过一些测试,我发现useranswers都返回 null,即没有找到用户。我不太明白为什么会这样,我还需要为搜索提供什么吗?我应该怎么办?

标签: javatomcatldapjndi

解决方案


推荐阅读