简体   繁体   中英

Check username and password in Ldap server through java

I have to check if username and password gave from user are right matching with the Ldap server. I use two connection, in the first I retrieve dn from uid and in the second I connect to Ldap with dn and password. I have a problem with retrieved dn, it doesn't have the right fields. It returns

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

and not

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

As you can see, ou and dc are not returned so my second query fails. This is my code

@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);
    }
}

with this parameters

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

I'm uing this value also for spring authentication but I have one method (send big file) that fails only if I use authentication so I would like to try to authenticate with java and not through Spring Do you know why I have this problem? thanks

UPDATE : with

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

it works, is my codes robust?

This is jboss LDAP login module implementation you can compare you code:

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)
   }

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