Package javax.naming.ldap

Examples of javax.naming.ldap.InitialLdapContext


   public List<String> listRoles()
   {
      List<String> roles = new ArrayList<String>();
     
      InitialLdapContext ctx = null;     
      try
      {
         ctx = initialiseContext();                      
        
         String[] roleAttr = { getRoleNameAttribute() };
                          
         SearchControls controls = new SearchControls();
         controls.setSearchScope(searchScope);
         controls.setReturningAttributes(roleAttr);
         controls.setTimeLimit(getSearchTimeLimit());
        
         StringBuilder roleFilter = new StringBuilder();
        
         Object[] filterArgs = new Object[getRoleObjectClasses().length];
         for (int i = 0; i < getRoleObjectClasses().length; i++)
         {
            roleFilter.append("(");
            roleFilter.append(getObjectClassAttribute());
            roleFilter.append("={");
            roleFilter.append(i);
            roleFilter.append("})");
            filterArgs[i] = getRoleObjectClasses()[i];
         }        
        
         NamingEnumeration answer = ctx.search( getRoleContextDN(), roleFilter.toString(),
               filterArgs, controls);
         while (answer.hasMore())
         {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute user = attrs.get( getRoleNameAttribute() );
           
            for (int i = 0; i < user.size(); i++)
            {
               Object value = user.get(i);
               roles.add(value.toString());
            }           
         }
         answer.close();
         return roles;        
      }
      catch (NamingException ex)
      {
         throw new IdentityManagementException("Error getting roles", ex);
      }
      finally
      {
         if (ctx != null)
         {
            try
            {
               ctx.close();
            }
            catch (NamingException ex) {}
         }
      }
   }
View Full Code Here


   public List<String> listUsers(String filter)
   {
      List<String> users = new ArrayList<String>();
     
      InitialLdapContext ctx = null;     
      try
      {
         ctx = initialiseContext();             
      
         String[] userAttr = {getUserNameAttribute()};
                          
         SearchControls controls = new SearchControls();
         controls.setSearchScope(searchScope);
         controls.setReturningAttributes(userAttr);
         controls.setTimeLimit(getSearchTimeLimit());
                 
         StringBuilder userFilter = new StringBuilder("(&");
        
         Object[] filterArgs = new Object[getUserObjectClasses().length];
         for (int i = 0; i < getUserObjectClasses().length; i++)
         {
            userFilter.append("(");
            userFilter.append(getObjectClassAttribute());
            userFilter.append("={");
            userFilter.append(i);
            userFilter.append("})");
            filterArgs[i] = getUserObjectClasses()[i];
         }           
        
         userFilter.append(")");
        
         NamingEnumeration answer = ctx.search(getUserContextDN(), userFilter.toString(), filterArgs, controls);
         while (answer.hasMore())
         {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute user = attrs.get(getUserNameAttribute());
           
            for (int i = 0; i < user.size(); i++)
            {
               Object value = user.get(i);
              
               if (filter != null)
               {
                  if (value.toString().toLowerCase().contains(filter.toLowerCase()))
                  {
                     users.add(value.toString());
                  }
               }
               else
               {              
                  users.add(value.toString());
               }
            }           
         }
         answer.close();
         return users;        
      }
      catch (NamingException ex)
      {
         throw new IdentityManagementException("Error getting users", ex);
      }
      finally
      {
         if (ctx != null)
         {
            try
            {
               ctx.close();
            }
            catch (NamingException ex) {}
         }
      }
   }
View Full Code Here

      }
   }

   public boolean userExists(String name)
   {
      InitialLdapContext ctx = null;     
      try
      {
         ctx = initialiseContext();             
      
         String[] userAttr = {getUserNameAttribute()};
                          
         SearchControls controls = new SearchControls();
         controls.setSearchScope(searchScope);
         controls.setReturningAttributes(userAttr);
         controls.setTimeLimit(getSearchTimeLimit());
                 
         StringBuilder userFilter = new StringBuilder();
        
         Object[] filterArgs = new Object[getUserObjectClasses().length];
         for (int i = 0; i < getUserObjectClasses().length; i++)
         {
            userFilter.append("(");
            userFilter.append(getObjectClassAttribute());
            userFilter.append("={");
            userFilter.append(i);
            userFilter.append("})");
            filterArgs[i] = getUserObjectClasses()[i];
         }           
        
         NamingEnumeration answer = ctx.search(getUserContextDN(), userFilter.toString(), filterArgs, controls);
         while (answer.hasMore())
         {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute user = attrs.get(getUserNameAttribute());
           
            for (int i = 0; i < user.size(); i++)
            {
               Object value = user.get(i);
               if (name.equals(value))
               {
                  answer.close();
                  return true;
               }
            }           
         }
         answer.close();
         return false;        
      }
      catch (NamingException ex)
      {
         throw new IdentityManagementException("Error getting users", ex);
      }
      finally
      {
         if (ctx != null)
         {
            try
            {
               ctx.close();
            }
            catch (NamingException ex) {}
         }
      }
   }
View Full Code Here

         Properties tmp = new Properties();
         tmp.putAll(env);
         tmp.setProperty(Context.SECURITY_CREDENTIALS, "***");
         log.trace("Logging into LDAP server, env=" + tmp.toString());
      }
      InitialLdapContext ctx = new InitialLdapContext(env, null);
      if( trace )
         log.trace("Logged into LDAP server, " + ctx);

      if( bindDN != null )
      {
         // Rebind the ctx to the bind dn/credentials for the roles searches
         if( trace )
            log.trace("Rebind SECURITY_PRINCIPAL to: "+bindDN);
         env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
         env.put(Context.SECURITY_CREDENTIALS, bindCredential);
         ctx = new InitialLdapContext(env, null);
      }

      /* If a userRolesCtxDNAttributeName was speocified, see if there is a
       user specific roles DN. If there is not, the default rolesCtxDN will
       be used.
       */
      String rolesCtxDN = (String) options.get(ROLES_CTX_DN_OPT);
      String userRolesCtxDNAttributeName = (String) options.get(USER_ROLES_CTX_DN_ATTRIBUTE_ID_OPT);
      if (userRolesCtxDNAttributeName != null)
      {
         // Query the indicated attribute for the roles ctx DN to use
         String[] returnAttribute = {userRolesCtxDNAttributeName};
         try
         {
            Attributes result = ctx.getAttributes(userDN, returnAttribute);
            if (result.get(userRolesCtxDNAttributeName) != null)
            {
               rolesCtxDN = result.get(userRolesCtxDNAttributeName).get().toString();
               super.log.trace("Found user roles context DN: " + rolesCtxDN);
            }
         }
         catch (NamingException e)
         {
            super.log.debug("Failed to query userRolesCtxDNAttributeName", e);
         }
      }

      // Search for any roles associated with the user
      if (rolesCtxDN != null)
      {
         String uidAttrName = (String) options.get(UID_ATTRIBUTE_ID_OPT);
         if (uidAttrName == null)
            uidAttrName = "uid";
         String roleAttrName = (String) options.get(ROLE_ATTRIBUTE_ID_OPT);
         if (roleAttrName == null)
            roleAttrName = "roles";
         StringBuffer roleFilter = new StringBuffer("(");
         roleFilter.append(uidAttrName);
         roleFilter.append("={0})");
         String userToMatch = username;
         if (matchOnUserDN == true)
            userToMatch = userDN;

         String[] roleAttr = {roleAttrName};
         // Is user's role attribute a DN or the role name
         String roleAttributeIsDNOption = (String) options.get(ROLE_ATTRIBUTE_IS_DN_OPT);
         boolean roleAttributeIsDN = Boolean.valueOf(roleAttributeIsDNOption).booleanValue();

         // If user's role attribute is a DN, what is the role's name attribute
         // Default to 'name' (Group name attribute in Active Directory)
         String roleNameAttributeID = (String) options.get(ROLE_NAME_ATTRIBUTE_ID_OPT);
         if (roleNameAttributeID == null)
            roleNameAttributeID = "name";

         int searchScope = SearchControls.SUBTREE_SCOPE;
         int searchTimeLimit = 10000;
         String timeLimit = (String) options.get(SEARCH_TIME_LIMIT_OPT);
         if( timeLimit != null )
         {
            try
            {
               searchTimeLimit = Integer.parseInt(timeLimit);
            }
            catch(NumberFormatException e)
            {
               log.trace("Failed to parse: "+timeLimit+", using searchTimeLimit="+searchTimeLimit);
            }
         }
         String scope = (String) options.get(SEARCH_SCOPE_OPT);
         if( "OBJECT_SCOPE".equalsIgnoreCase(scope) )
            searchScope = SearchControls.OBJECT_SCOPE;
         else if( "ONELEVEL_SCOPE".equalsIgnoreCase(scope) )
            searchScope = SearchControls.ONELEVEL_SCOPE;
         if( "SUBTREE_SCOPE".equalsIgnoreCase(scope) )
            searchScope = SearchControls.SUBTREE_SCOPE;

         try
         {
            SearchControls controls = new SearchControls();
            controls.setSearchScope(searchScope);
            controls.setReturningAttributes(roleAttr);
            controls.setTimeLimit(searchTimeLimit);
            Object[] filterArgs = {userToMatch};
            if( trace )
            {
               log.trace("searching rolesCtxDN="+rolesCtxDN+", roleFilter="+roleFilter
                  +", filterArgs="+userToMatch+", roleAttr="+roleAttr
                  +", searchScope="+searchScope+", searchTimeLimit="+searchTimeLimit
               );
            }
            NamingEnumeration answer = ctx.search(rolesCtxDN, roleFilter.toString(),
               filterArgs, controls);
            while (answer.hasMore())
            {
               SearchResult sr = (SearchResult) answer.next();
               if( trace )
               {
                  log.trace("Checking answer: "+sr.getName());
               }
               Attributes attrs = sr.getAttributes();
               Attribute roles = attrs.get(roleAttrName);
               for (int r = 0; r < roles.size(); r++)
               {
                  Object value = roles.get(r);
                  String roleName = null;
                  if (roleAttributeIsDN == true)
                  {
                     // Query the roleDN location for the value of roleNameAttributeID
                     String roleDN = value.toString();
                     String[] returnAttribute = {roleNameAttributeID};
                     if( trace )
                        log.trace("Following roleDN: " + roleDN);
                     try
                     {
                        Attributes result2 = ctx.getAttributes(roleDN, returnAttribute);
                        Attribute roles2 = result2.get(roleNameAttributeID);
                        if( roles2 != null )
                        {
                           for(int m = 0; m < roles2.size(); m ++)
                           {
                              roleName = (String) roles2.get(m);
                              addRole(roleName);
                           }
                        }
                     }
                     catch (NamingException e)
                     {
                        log.trace("Failed to query roleNameAttrName", e);
                     }
                  }
                  else
                  {
                     // The role attribute value is the role name
                     roleName = value.toString();
                     addRole(roleName);
                  }
               }
            }
            answer.close();
         }
         catch (NamingException e)
         {
            if( trace )
               log.trace("Failed to locate roles", e);
         }
      }
      // Close the context to release the connection
      ctx.close();
   }
View Full Code Here

         searchScope = SearchControls.ONELEVEL_SCOPE;
      if ("SUBTREE_SCOPE".equalsIgnoreCase(scope))
         searchScope = SearchControls.SUBTREE_SCOPE;

      // Get the admin context for searching
      InitialLdapContext ctx = null;
      try
      {
         ctx = constructInitialLdapContext(bindDN, bindCredential);
         // Validate the user by binding against the userDN
         String userDN = bindDNAuthentication(ctx, username, credential, baseDN, baseFilter);

         // Query for roles matching the role filter
         SearchControls constraints = new SearchControls();
         constraints.setSearchScope(searchScope);
         constraints.setReturningAttributes(new String[0]);
         constraints.setTimeLimit(searchTimeLimit);
         rolesSearch(ctx, constraints, username, userDN, recursion, 0);
      }
      finally
      {
         if( ctx != null )
            ctx.close();
      }
      return true;
   }
View Full Code Here

         throw new NamingException("Can't follow referal for authentication: " + name);

      results.close();
      results = null;
      // Bind as the user dn to authenticate the user
      InitialLdapContext userCtx = constructInitialLdapContext(userDN, credential);
      userCtx.close();

      return userDN;
   }
View Full Code Here

      if (dn != null)
         env.setProperty(Context.SECURITY_PRINCIPAL, dn);
      if (credential != null)
         env.put(Context.SECURITY_CREDENTIALS, credential);
      traceLdapEnv(env);
      return new InitialLdapContext(env, null);
   }
View Full Code Here

                + ((ldapPort == null) ? "" : (":" + ldapPort)));
        StartTlsResponse tlsResponse = null;
        LdapContext ctx = null;

        try {
            ctx = new InitialLdapContext(env, null);

            if (tls) {
                // Requesting to start TLS on an LDAP association
                tlsResponse = (StartTlsResponse) ctx.extendedOperation(
                        new StartTlsRequest());
View Full Code Here

            systemConfig.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
            systemConfig.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
        }

        try {
            InitialLdapContext ctx = new InitialLdapContext(systemConfig, null);
            SearchControls searchControls = getSearchControls();

            // Add the search filter if specified.  This only allows for a single search filter.. i.e. foo=bar.
            String filter;
            if ((searchFilter != null) && (searchFilter.length() != 0)) {
                filter = "(&(" + loginProperty + "=" + userName + ")" + "(" + searchFilter + "))";
            } else {
                filter = "(" + loginProperty + "=" + userName + ")";
            }

            log.debug("Using LDAP filter [" + filter + "] to locate user details for " + userName);

            // Loop through each configured base DN.  It may be useful
            // in the future to allow for a filter to be configured for
            // each BaseDN, but for now the filter will apply to all.
            String[] baseDNs = baseDN.split(BASEDN_DELIMITER);
            for (int x = 0; x < baseDNs.length; x++) {
                NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls);
                if (!answer.hasMoreElements()) { //BZ:582471- ldap api bug change
                    log.debug("User " + userName + " not found for BaseDN " + baseDNs[x]);
                    // Nothing found for this DN, move to the next one if we have one.
                    continue;
                }
View Full Code Here

            systemConfig.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
            systemConfig.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
            systemConfig.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
        }
        try {
            InitialLdapContext ctx = new InitialLdapContext(systemConfig, null);
            ctx.close();
        } catch (NamingException e) {
            requiresAttention = true;
            log.error("LDAP communication error: " + e.getMessage(), e);
        }
View Full Code Here

TOP

Related Classes of javax.naming.ldap.InitialLdapContext

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.