通过java检查Ldap服务器中的用户名和密码

时间:2016-01-12 09:54:17

标签: java authentication ldap distinguishedname

我必须检查用户提供的用户名和密码是否与Ldap服务器正确匹配。我使用两个连接,在第一个我从uid检索dn,在第二个我用dn和密码连接到Ldap。 检索到的dn有问题,它没有正确的字段。 它返回

cn=Lu Ca+sn=Ca+uid=luca+userPassword={SSHA}OiMBVTTZBPqnohYch9\+ISeVv\+5ucgxMR: null:null:No attributes

而不是

cn=Lu Ca+sn=Ca+uid=luca+userPassword={SSHA}OiMBVTTZBPqnohYch9\+ISeVv\+5ucgxMR,ou=people,dc=example,dc=com

如您所见,未返回ou和dc,因此我的第二个查询失败。 这是我的代码

@Override
public void isAuthenticated(String username, String password) throws LdapException{
    String dn;
    Hashtable<String, Object> ldapEnv = new Hashtable<String, Object>();
    ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    ldapEnv.put(Context.PROVIDER_URL, env.getRequiredProperty(PROPERTY_NAME_LDAP_URL));
    ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
    ldapEnv.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    ldapEnv.put(Context.SECURITY_CREDENTIALS, "secret");
    String[] returnAttribute = {"dn"};
    DirContext ctx = null;
    NamingEnumeration<SearchResult> results = null;
    try {
        ctx = new InitialDirContext(ldapEnv);
        SearchControls controls = new SearchControls();
        controls.setReturningAttributes(returnAttribute);
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String filter = "uid=" + username ;
        results = ctx.search(env.getRequiredProperty(PROPERTY_NAME_LDAP_USERSEARCHBASE), filter, controls);
        if (results.hasMore())
            dn = results.nextElement().toString();
        else throw new LdapException("Wrong username. Please retry!");
    } catch (Exception e) {
        throw new LdapException(e);
    } finally {
        try{
            if (results != null)
                results.close();             
            if (ctx != null) 
                ctx.close();
        }catch(Exception e){
            throw new LdapException(e);
        }
    }
    Hashtable<String, Object> authEnv = new Hashtable<String, Object>();
    authEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
    authEnv.put(Context.PROVIDER_URL, env.getRequiredProperty(PROPERTY_NAME_LDAP_URL));
    authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
    authEnv.put(Context.SECURITY_PRINCIPAL, dn);
    authEnv.put(Context.SECURITY_CREDENTIALS, password);
    try {
        new InitialDirContext(authEnv);
    } catch (AuthenticationException authEx) {
        throw new LdapException("Authentication error. Password was wrong");
    } catch(Exception e){
        throw new LdapException(e);
    }
}

使用此参数

ldap.url=ldap://127.0.0.1:10389/dc=example,dc=com
ldap.userSearchBase=ou=people

我也正在使用这个值进行spring身份验证,但我有一个方法(发送大文件)只有在我使用身份验证时才会失败,所以我想尝试使用java进行身份验证而不是通过Spring进行身份验证 你知道为什么我有这个问题吗?感谢

更新 :带

dn = results.nextElement().getNameInNamespace();

它有效,我的代码是否健壮?

1 个答案:

答案 0 :(得分:0)

这是jboss LDAP登录模块的实现,你可以比较你的代码:

full code link

  protected void rolesSearch(LdapContext ctx, SearchControls constraints, String user, String userDN,
         int recursionMax, int nesting) throws NamingException
   {
      LdapContext ldapCtx = ctx;

      Object[] filterArgs = {user, sanitizeDN(userDN)};
      boolean referralsExist = true;
      while (referralsExist) {
         NamingEnumeration results = ldapCtx.search(rolesCtxDN, roleFilter, filterArgs, constraints);
         try
         {
            while (results.hasMore())
            {
               SearchResult sr = (SearchResult) results.next();

               String dn;
               if (sr.isRelative()) {
                  dn = canonicalize(sr.getName());
               }
               else {
                  dn = sr.getNameInNamespace();
               }
               if (nesting == 0 && roleAttributeIsDN && roleNameAttributeID != null)
               {
                  if(parseRoleNameFromDN)
                  {
                     parseRole(dn);
                  }
                  else
                  {
                     // Check the top context for role names
                     String[] attrNames = {roleNameAttributeID};
                     Attributes result2 = null;
                     if (sr.isRelative()) {
                        result2 = ldapCtx.getAttributes(quoteDN(dn), attrNames);
                     }
                     else {
                        result2 = getAttributesFromReferralEntity(sr, user, userDN);
                     }
                     Attribute roles2 = (result2 != null ? result2.get(roleNameAttributeID) : null);
                     if( roles2 != null )
                     {
                        for(int m = 0; m < roles2.size(); m ++)
                        {
                           String roleName = (String) roles2.get(m);
                           addRole(roleName);
                        }
                     }
                  }
               }

               // Query the context for the roleDN values
               String[] attrNames = {roleAttributeID};
               Attributes result = null;
               if (sr.isRelative()) {
                  result = ldapCtx.getAttributes(quoteDN(dn), attrNames);
               }
               else {
                  result = getAttributesFromReferralEntity(sr, user, userDN); 
               }
               if (result != null && result.size() > 0)
               {
                  Attribute roles = result.get(roleAttributeID);
                  for (int n = 0; n < roles.size(); n++)
                  {
                     String roleName = (String) roles.get(n);
                     if(roleAttributeIsDN && parseRoleNameFromDN)
                     {
                         parseRole(roleName);
                     }
                     else if (roleAttributeIsDN)
                     {
                        // Query the roleDN location for the value of roleNameAttributeID
                        String roleDN = quoteDN(roleName);
                        String[] returnAttribute = {roleNameAttributeID};
                        try
                        {
                           Attributes result2 = null;
                           if (sr.isRelative()) {
                              result2 = ldapCtx.getAttributes(roleDN, returnAttribute);
                           }
                           else {
                              result2 = getAttributesFromReferralEntity(sr, user, userDN);
                           }

                           Attribute roles2 = (result2 != null ? result2.get(roleNameAttributeID) : null);
                           if (roles2 != null)
                           {
                              for (int m = 0; m < roles2.size(); m++)
                              {
                                 roleName = (String) roles2.get(m);
                                 addRole(roleName);
                              }
                           }
                        }
                        catch (NamingException e)
                        {
                           PicketBoxLogger.LOGGER.debugFailureToQueryLDAPAttribute(roleNameAttributeID, roleDN, e);
                        }
                     }
                     else
                     {
                        // The role attribute value is the role name
                        addRole(roleName);
                     }
                  }
               }

               if (nesting < recursionMax)
               {
                  rolesSearch(ldapCtx, constraints, user, dn, recursionMax, nesting + 1);
               }
            }
            referralsExist = false;
         }
         catch (ReferralException e) {
            ldapCtx = (LdapContext) e.getReferralContext();
         }
         finally
         {
            if (results != null)
               results.close();
         }
      } // while (referralsExist)
   }