Package javax.naming.ldap

Examples of javax.naming.ldap.InitialLdapContext


            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);
            SearchControls searchControls = getSearchControls();
            /*String filter = "(&(objectclass=groupOfUniqueNames)(uniqueMember=uid=" + userName
                + ",ou=People, dc=rhndev, dc=redhat, dc=com))";*/

            //modify the search control to only include the attributes we will use
            String[] attributes = { "cn", "description" };
            searchControls.setReturningAttributes(attributes);

            //detect whether to use Query Page Control
            String groupUseQueryPaging = systemConfig.getProperty(SystemSetting.LDAP_GROUP_PAGING.name(),
                "false");
            if (groupUseQueryPaging == null) {
                groupUseQueryPaging = Boolean.toString(false);//default to false
            }
            boolean useQueryPaging = Boolean.valueOf(groupUseQueryPaging);

            //BZ:964250: add rfc 2696
            //default to 1000 results.  System setting page size from UI should be non-negative integer > 0.
            //additionally as system settings are modifiable via CLI which may not have param checking enabled do some
            //more checking.
            int defaultPageSize = 1000;
            // only if they're enabled in the UI.
            if (useQueryPaging) {
                String groupPageSize = systemConfig.getProperty(
SystemSetting.LDAP_GROUP_QUERY_PAGE_SIZE.name(), ""
                    + defaultPageSize);
                if ((groupPageSize != null) && (!groupPageSize.trim().isEmpty())) {
                    int passedInPageSize = -1;
                    try {
                        passedInPageSize = Integer.valueOf(groupPageSize.trim());
                        if ((passedInPageSize > 0) && (passedInPageSize <= LDAP_GROUP_QUERY_LIMIT)) {
                            defaultPageSize = passedInPageSize;
                        } else {//keep defaults and log actual value being used.
                            log.debug("LDAP Group Page Size passed '" + groupPageSize
                                + "' was ignored. Defaulting to 1000.");
                        }
                    } catch (NumberFormatException nfe) {
                        //log issue and do nothing. Go with the default.
                        log.debug("LDAP Group Page Size passed '" + groupPageSize
                            + "' in is invalid. Defaulting to 1000." + nfe.getMessage());
                    }
                }
                ctx.setRequestControls(new Control[] { new PagedResultsControl(defaultPageSize, Control.CRITICAL) });
            }
            // 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++) {
                //update query start time
                groupQueryStartTime = System.currentTimeMillis();

                executeGroupSearch(filter, groupDetailsMap, ctx, searchControls, baseDNs, x);

                //update queryResultCount
                groupQueryResultCount = groupDetailsMap.size();
                groupQueryCurrentTime = System.currentTimeMillis();

                // continually parsing pages of results until we're done.
                // only if they're enabled in the UI.
                if (useQueryPaging) {

                    //handle paged results if they're being used here
                    byte[] cookie = null;
                    Control[] controls = ctx.getResponseControls();
                    if (controls != null) {
                        for (Control control : controls) {
                            if (control instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl pagedResult = (PagedResultsResponseControl) control;
                                cookie = pagedResult.getCookie();
                            }
                        }
                    }
                    //continually parsing pages of results until we're done.
                    while ((groupQueryResultCount <= LDAP_GROUP_QUERY_LIMIT) && (cookie != null)) {
                        //ensure the next requests contains the session/cookie details
                        ctx.setRequestControls(new Control[] { new PagedResultsControl(defaultPageSize, cookie,
                            Control.CRITICAL) });
                        executeGroupSearch(filter, groupDetailsMap, ctx, searchControls, baseDNs, x);

                        //update Query state after each page
                        groupQueryResultCount = groupDetailsMap.size();
                        groupQueryPageCount++;
                        groupQueryCurrentTime = System.currentTimeMillis();

                        //empty out cookie
                        cookie = null;
                        //insert group query throttle.
                            //test for further iterations
                            controls = ctx.getResponseControls();
                            if (controls != null) {
                                for (Control control : controls) {
                                    if (control instanceof PagedResultsResponseControl) {
                                        PagedResultsResponseControl pagedResult = (PagedResultsResponseControl) control;
                                        cookie = pagedResult.getCookie();
View Full Code Here


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

        LOG.debug("Validating LDAP properties. Initializing context...");
        new InitialLdapContext(env, null).close();

        return;
    }
View Full Code Here

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

        try {
            InitialLdapContext ctx = new InitialLdapContext(env, 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);

            // 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 answer = ctx.search(baseDNs[x], filter, searchControls);
                boolean ldapApiNpeFound = false;
                if (!answer.hasMoreElements()) {//BZ:582471- ldap api bug
                    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;
                }

                // We use the first match
                SearchResult si = (SearchResult) answer.next();

                // Construct the UserDN
                String userDN = null;

                try {
                    userDN = si.getNameInNamespace();
                } catch (UnsupportedOperationException use) {
                    userDN = new CompositeName(si.getName()).get(0);
                    if (si.isRelative()) {
                        userDN += "," + baseDNs[x];
                    }
                }

                log.debug("Using LDAP userDN=" + userDN);

                ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
                ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inputPassword);
                ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");

                //if successful then verified that user and pw are valid ldap credentials
                ctx.reconnect(null);

                return true;
            }

            // If we try all the BaseDN's and have not found a match, return false
View Full Code Here

              + keys[6] + " cannot be empty to proceed.";
          log(msg);
          proceed = false;
        }
        env = null;
        InitialLdapContext ctx = null;
        if (proceed) {// attempt initial ldap bind from RHQ server
          msg = "STEP-1:TESTING: Attempting to bind to server:" + ldapServer
              + "\n with user '" + bindUserName
              + "' and password entered.";
          log(msg);
          env = getProperties(ldapServer);
          env.setProperty(Context.SECURITY_PRINCIPAL, bindUserName);
          env.setProperty(Context.SECURITY_CREDENTIALS, bindPassword);
          env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
          //put the rest of the LDAP properties into the Properties instance for use later.
          //there still needs to be separate variables since some are for UI validation.
          env.setProperty(SystemSetting.LDAP_GROUP_FILTER.getInternalName(), groupSearchFilter);
          env.setProperty(SystemSetting.LDAP_GROUP_MEMBER.getInternalName(), groupMemberFilter);
          env.setProperty(SystemSetting.LDAP_BASE_DN.getInternalName(), searchBase);
          env.setProperty(SystemSetting.LDAP_LOGIN_PROPERTY.getInternalName(), loginProperty);
          env.setProperty(SystemSetting.LDAP_BIND_DN.getInternalName(), bindUserName);
          env.setProperty(SystemSetting.LDAP_BIND_PW.getInternalName(), bindPassword);
          env.setProperty(SystemSetting.LDAP_GROUP_QUERY_PAGE_SIZE.getInternalName(), groupMemberQuerySize);
         
          try {
            ctx = new InitialLdapContext(env, null);
            msg = "STEP-1:PASS: LDAP bind credentials are correct. Successfully connected to '"
                + ldapServer
                + "'.\n This means the LDAP Bind credentials for the RHQ Server authentication/authorization requests to ldap server "
                    + "are correct.";
            if(enableVerboseDebugging.isSelected()){
              msg+="\n"+advdb+" LDAP simple authentication bind successful.";
            }
            log(msg);
            proceed = true;
          } catch (Exception ex) {
            msg = "STEP-1:FAIL: Unable to connect to the LDAP server with credentials specified.\n";
            msg+="Exception:"+ex.getMessage();
            if(enableVerboseDebugging.isSelected()){
              msg = appendStacktraceToMsg(msg, ex);
            }
            log(msg);
            proceed = false;
          }
        }
        if (proceed) {// retrieve test credentials to test run auth
          // load search controls
          SearchControls searchControls = getSearchControls();
          // validating searchFilter and test user/pass creds
          proceed = true;
          if (testUserName.isEmpty() || (testUserPassword.isEmpty())) {
            msg = "STEP-2:FAIL: Test Username/Password fields cannot be empty for this step.";
            log(msg);
            proceed = false;
          }
          // testing a valid user involves a filtered ldap search
          // using the loginProperty, and optionally searchFilter
                    userDN = "";
          if (proceed) {
            // default loginProperty to cn if it's not set
            if (loginProperty.isEmpty()) {
              loginProperty = "cn";
              if(enableVerboseDebugging.isSelected()){
                String mesg = "As you have not specified a login property, defaulting to 'cn'";
                log(advdb+" "+msg);
              }
            }
            String filter;
            if (!searchFilter.isEmpty()) {
              filter = "(&(" + loginProperty + "=" + testUserName
                  + ")" + "(" + searchFilter + "))";
            } else {
              filter = "(" + loginProperty + "=" + testUserName
                  + ")";
            }
            if(enableVerboseDebugging.isSelected()){
              log(advdb+" The searchfilter is optionally appended to login property for additional shared attribute across users.");
            }
            msg = "STEP-2:TESTING: To validate the test user the following LDAP filtered component will be used to find matching users:\n";
            msg += filter;
            log(msg);
            // test out the search on the target ldap server
            try {
              String[] baseDNs = searchBase.split(";");
              for (int x = 0; x < baseDNs.length; x++) {
                NamingEnumeration answer = ctx.search(
                    baseDNs[x], filter, searchControls);
                if(enableVerboseDebugging.isSelected()){
                  log(advdb+" this search was excuted against DN component '"+baseDNs[x]+"'.");
                }
                // boolean ldapApiNpeFound = false;
                if (!answer.hasMoreElements()) {
                  msg="STEP-2:WARN Unable to locate a matching users for the filter'"+filter+
                  "'. Please check your loginProperty. Usually 'cn' or 'uid'";
                  log(msg);
                  continue;
                }
                // Going with the first match
                SearchResult si = (SearchResult) answer.next();

                constructUserDn(baseDNs, x, si);

                msg = "STEP-2:PASS: The test user '"
                    + testUserName
                    + "' was succesfully located, and the following userDN will be used in authorization check:\n";
                msg += userDN;
                log(msg);

                ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
                ctx.addToEnvironment(Context.SECURITY_CREDENTIALS,testUserPassword);
                ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION,"simple");

                // if successful then verified that user and pw
                // are valid ldap credentials
                ctx.reconnect(null);
                msg = "STEP-2:PASS: The user '"
                    + testUserName
                    + "' was succesfully authenticated using userDN '"
                    + userDN + "' and password provided.\n"
                    +"*Note: the loginProperty must match the loginProperty listed in dn: for the user. It is the DN that RHQ will lookup and use.";
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);
            SearchControls searchControls = getSearchControls();
            /*String filter = "(&(objectclass=groupOfUniqueNames)(uniqueMember=uid=" + userName
                + ",ou=People, dc=rhndev, dc=redhat, dc=com))";*/

            //modify the search control to only include the attributes we will use
            String[] attributes = { "cn", "description" };
            searchControls.setReturningAttributes(attributes);

            //BZ:964250: add rfc 2696
            //default to 1000 results.  System setting page size from UI should be non-negative integer > 0.
            //additionally as system settings are modifiable via CLI which may not have param checking enabled do some
            //more checking.
            int defaultPageSize = 1000;
            // only if they're enabled in the UI.
      if (enable32xFeatures.isSelected()) {
        String groupPageSize = systemConfig.getProperty(
            SystemSetting.LDAP_GROUP_QUERY_PAGE_SIZE
                .getInternalName(), "" + defaultPageSize);
        if ((groupPageSize != null)
            && (!groupPageSize.trim().isEmpty())) {
          int passedInPageSize = -1;
          try {
            passedInPageSize = Integer
                .valueOf(groupPageSize.trim());
            if (passedInPageSize > 0) {
              defaultPageSize = passedInPageSize;
              if(enableVerboseDebugging.isSelected()){
                log(advdb
                    + " LDAP Group Query Page Sizing of '"+defaultPageSize+"' is being requested from server.");
              }
            }
          } catch (NumberFormatException nfe) {
            // log issue and do nothing. Go with the default.
            String msg = "LDAP Group Page Size passed in '"
                + groupPageSize
                + "' in is invalid. Defaulting to 1000 results."
                + nfe.getMessage();
            log(msg);
          }
        }
        ctx.setRequestControls(new Control[] { new PagedResultsControl(
            defaultPageSize, Control.CRITICAL) });
      }
            // 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++) {
        if (enableVerboseDebugging.isSelected()) {
          log(advdb
              + " this search was excuted against DN component '"
              + baseDNs[x] + "'.");
        }
                executeGroupSearch(filter, groupDetailsMap, ctx, searchControls, baseDNs, x);

        // continually parsing pages of results until we're done.
                // only if they're enabled in the UI.
        if (enable32xFeatures.isSelected()) {
          // handle paged results if they're being used here
          byte[] cookie = null;
          Control[] controls = ctx.getResponseControls();
          if (controls != null) {
            for (Control control : controls) {
              if (control instanceof PagedResultsResponseControl) {
                PagedResultsResponseControl pagedResult = (PagedResultsResponseControl) control;
                cookie = pagedResult.getCookie();
              }
            }
          }

          while (cookie != null) {
            String msg = "RFC 2696 is supported by the server and we are paging through the results. "+
                groupDetailsMap.size()+" results returned so far.";
            if(enableVerboseGroupParsing.isSelected()){
              log(advdb
                  + msg);
            }
            // ensure the next requests contains the session/cookie
            // details
            ctx.setRequestControls(new Control[] { new PagedResultsControl(
                defaultPageSize, cookie, Control.CRITICAL) });
            executeGroupSearch(filter, groupDetailsMap, ctx,
                searchControls, baseDNs, x);
            // empty out cookie
            cookie = null;
            // test for further iterations
            controls = ctx.getResponseControls();
            if (controls != null) {
              for (Control control : controls) {
                if (control instanceof PagedResultsResponseControl) {
                  PagedResultsResponseControl pagedResult = (PagedResultsResponseControl) control;
                  cookie = pagedResult.getCookie();
View Full Code Here

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

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

      String filter = String.format("(&(%s)(%s=%s))",
      groupSearchFilter, groupMemberFilter,
            //      testUserDN); BZ 707047
                encodeForFilter(testUserDN));

          generateUiLoggingForStep4LdapFilter(userName, filter);
           
            // 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
                    // Nothing found for this DN, move to the next one if we have one.
                    continue;
                }
View Full Code Here

  if (authMethod != null && ! authMethod.equals("none")) {
      env.put(Context.SECURITY_PRINCIPAL, principal);
      env.put(Context.SECURITY_CREDENTIALS, credentials);
  }

        DirContext ctx = new InitialLdapContext(env, null);

        log.info("Finished binding principal.");

        return ctx;
    }
View Full Code Here

        env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
        env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
        env.put( Context.SECURITY_PRINCIPAL, ServerDNConstants.ADMIN_SYSTEM_DN );
        env.put( Context.SECURITY_CREDENTIALS, "secret" );
        env.put( Context.SECURITY_AUTHENTICATION, "simple" );
        return new InitialLdapContext( env, JndiUtils.toJndiControls( LdapApiServiceFactory.getSingleton(), controls ) );
    }
View Full Code Here

        fac);
   
    Properties props = new Properties();
    props.put(JNDIConstants.BUNDLE_CONTEXT, bc);
    props.put(Context.INITIAL_CONTEXT_FACTORY, "dummy.factory");
    InitialLdapContext ilc = new InitialLdapContext(props, new Control[0]);
   
    ExtendedRequest req = Skeleton.newMock(ExtendedRequest.class);
    ilc.extendedOperation(req);
    Skeleton.getSkeleton(backCtx).assertCalled(new MethodCall(LdapContext.class, "extendedOperation", req));
  }
View Full Code Here

        }
        if (logger.isDebugEnabled ()) {
            logger.debug ("Logging into LDAP server, env=" + env);
        }
        try {
            ctx = new InitialLdapContext(env, null);
        } catch (NamingException e) {
            throw new FactoryConfigurationError
                ("Cannot create LDAP connection: " + 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.