Example usage for javax.naming.ldap InitialLdapContext InitialLdapContext

List of usage examples for javax.naming.ldap InitialLdapContext InitialLdapContext

Introduction

In this page you can find the example usage for javax.naming.ldap InitialLdapContext InitialLdapContext.

Prototype

@SuppressWarnings("unchecked")
public InitialLdapContext(Hashtable<?, ?> environment, Control[] connCtls) throws NamingException 

Source Link

Document

Constructs an initial context using environment properties and connection request controls.

Usage

From source file:org.rhq.enterprise.server.core.CustomJaasDeploymentService.java

private void validateLdapOptions(Map<String, String> options) throws NamingException {
    Properties env = new Properties();

    String factory = options.get(Context.INITIAL_CONTEXT_FACTORY);
    if (factory == null) {
        throw new NamingException("No initial context factory");
    }// w w w.ja  v  a  2s.  c o m

    String url = options.get(Context.PROVIDER_URL);
    if (url == null) {
        throw new NamingException("Naming provider url not set");
    }

    String protocol = options.get(Context.SECURITY_PROTOCOL);
    if ("ssl".equals(protocol)) {
        String ldapSocketFactory = env.getProperty("java.naming.ldap.factory.socket");
        if (ldapSocketFactory == null) {
            env.put("java.naming.ldap.factory.socket", UntrustedSSLSocketFactory.class.getName());
        }
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factory);
    env.setProperty(Context.PROVIDER_URL, url);

    // Load any information we may need to bind
    String bindDN = options.get("BindDN");
    String bindPW = options.get("BindPW");
    if ((bindDN != null) && (bindDN.length() != 0) && (bindPW != null) && (bindPW.length() != 0)) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        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;
}

From source file:org.rhq.enterprise.server.core.jaas.LdapLoginModule.java

/**
 * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#validatePassword(java.lang.String,java.lang.String)
 *//*from  w w  w  . j  ava 2  s  . c  o  m*/
protected boolean validatePassword(String inputPassword, String expectedPassword) {
    // Load our LDAP specific properties
    Properties env = getProperties();

    // Load the BaseDN
    String baseDN = (String) options.get("BaseDN");
    if (baseDN == null) {
        // If the BaseDN is not specified, log an error and refuse the login attempt
        log.info("BaseDN is not set, refusing login");
        return false;
    }

    // Many LDAP servers allow bind's with an emtpy password. We will deny all requests with empty passwords
    if ((inputPassword == null) || inputPassword.equals("")) {
        log.debug("Empty password, refusing login");
        return false;
    }

    // Load the LoginProperty
    String loginProperty = (String) options.get("LoginProperty");
    if (loginProperty == null) {
        // Use the default
        loginProperty = "cn";
    }

    // Load any search filter
    String searchFilter = (String) options.get("Filter");

    // Find the user that is calling us
    String userName = getUsername();

    // Load any information we may need to bind
    String bindDN = (String) options.get("BindDN");
    String bindPW = (String) options.get("BindPW");
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        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 = si.getName() + "," + baseDNs[x];

            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
        return false;
    } catch (Exception e) {
        log.info("Failed to validate password: " + e.getMessage());
        return false;
    }
}

From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java

public Map<String, String> findLdapUserDetails(String userName) {
    Properties systemConfig = systemManager.getSystemConfiguration(subjectManager.getOverlord());
    HashMap<String, String> userDetails = new HashMap<String, String>();
    // Load our LDAP specific properties
    Properties env = getProperties(systemConfig);

    // Load the BaseDN
    String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN);

    // Load the LoginProperty
    String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty);
    if (loginProperty == null) {
        // Use the default
        loginProperty = "cn";
    }//from   w  w  w .  ja v a  2  s.  co m
    // Load any information we may need to bind
    String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN);
    String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW);

    // Load any search filter
    String searchFilter = (String) systemConfig.get(RHQConstants.LDAPFilter);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        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 + "] 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;
            }

            // We use the first match
            SearchResult si = answer.next();
            //generate the DN
            String userDN = null;
            try {
                userDN = si.getNameInNamespace();
            } catch (UnsupportedOperationException use) {
                userDN = si.getName();
                if (userDN.startsWith("\"")) {
                    userDN = userDN.substring(1, userDN.length());
                }
                if (userDN.endsWith("\"")) {
                    userDN = userDN.substring(0, userDN.length() - 1);
                }
                userDN = userDN + "," + baseDNs[x];
            }
            userDetails.put("dn", userDN);

            // Construct the UserDN
            NamingEnumeration<String> keys = si.getAttributes().getIDs();
            while (keys.hasMore()) {
                String key = keys.next();
                Attribute value = si.getAttributes().get(key);
                if ((value != null) && (value.get() != null)) {
                    userDetails.put(key, value.get().toString());
                }
            }
            return userDetails;
        }
        return userDetails;
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java

/**
 * @throws NamingException//from w w w  .  j a va2  s  . c o  m
 * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#validatePassword(java.lang.String,java.lang.String)
 */
protected Set<Map<String, String>> buildGroup(Properties systemConfig, String filter) {
    Set<Map<String, String>> ret = new HashSet<Map<String, String>>();
    // Load our LDAP specific properties
    Properties env = getProperties(systemConfig);

    // Load the BaseDN
    String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN);

    // Load the LoginProperty
    String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty);
    if (loginProperty == null) {
        // Use the default
        loginProperty = "cn";
    }
    // Load any information we may need to bind
    String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN);
    String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }
    try {
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        SearchControls searchControls = getSearchControls();
        /*String filter = "(&(objectclass=groupOfUniqueNames)(uniqueMember=uid=" + userName
        + ",ou=People, dc=rhndev, dc=redhat, dc=com))";*/

        // 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);
            boolean ldapApiEnumerationBugEncountered = false;
            while ((!ldapApiEnumerationBugEncountered) && answer.hasMoreElements()) {//BZ:582471- ldap api bug change
                // We use the first match
                SearchResult si = null;
                try {
                    si = answer.next();
                } catch (NullPointerException npe) {
                    ldapApiEnumerationBugEncountered = true;
                    break;
                }
                Map<String, String> entry = new HashMap<String, String>();
                String name = (String) si.getAttributes().get("cn").get();
                name = name.trim();
                Attribute desc = si.getAttributes().get("description");
                String description = desc != null ? (String) desc.get() : "";
                description = description.trim();
                entry.put("id", name);
                entry.put("name", name);
                entry.put("description", description);
                ret.add(entry);
            }
        }
    } catch (NamingException e) {
        if (e instanceof InvalidSearchFilterException) {
            InvalidSearchFilterException fException = (InvalidSearchFilterException) e;
            String message = "The ldap group filter defined is invalid ";
            log.error(message, fException);
            throw new LdapFilterException(message + " " + fException.getMessage());
        }
        //TODO: check for ldap connection/unavailable/etc. exceptions.
        else {
            log.error("LDAP communication error: " + e.getMessage(), e);
            throw new LdapCommunicationException(e);
        }
    }

    return ret;
}

From source file:org.sonar.plugins.activedirectory.server.ApacheDS.java

@SuppressWarnings("unused")
private ApacheDS startKerberos() throws Exception {
    Preconditions.checkState(ldapServer.isStarted());

    kdcServer.setDirectoryService(directoryService);
    // FIXME hard-coded ports
    kdcServer.setTransports(new TcpTransport(6088), new UdpTransport(6088));
    kdcServer.setEnabled(true);//from w w w . ja v a2s  . c o  m
    kdcServer.setPrimaryRealm(realm);
    kdcServer.setSearchBaseDn(baseDn);
    kdcServer.setKdcPrincipal("krbtgt/" + realm + "@" + baseDn);
    kdcServer.start();

    // -------------------------------------------------------------------
    // Enable the krb5kdc schema
    // -------------------------------------------------------------------

    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(DirectoryService.JNDI_KEY, directoryService);
    env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
    env.put(Context.PROVIDER_URL, ServerDNConstants.OU_SCHEMA_DN);
    InitialLdapContext schemaRoot = new InitialLdapContext(env, null);

    // check if krb5kdc is disabled
    Attributes krb5kdcAttrs = schemaRoot.getAttributes("cn=Krb5kdc");
    boolean isKrb5KdcDisabled = false;
    if (krb5kdcAttrs.get("m-disabled") != null) {
        isKrb5KdcDisabled = ((String) krb5kdcAttrs.get("m-disabled").get()).equalsIgnoreCase("TRUE");
    }

    // if krb5kdc is disabled then enable it
    if (isKrb5KdcDisabled) {
        Attribute disabled = new BasicAttribute("m-disabled");
        ModificationItem[] mods = new ModificationItem[] {
                new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled) };
        schemaRoot.modifyAttributes("cn=Krb5kdc", mods);
    }
    return this;
}

From source file:org.sonar.plugins.ldap.LdapContextFactory.java

private InitialDirContext createInitialDirContext(String principal, String credentials, boolean pooling)
        throws NamingException {
    final InitialLdapContext ctx;
    if (startTLS) {
        // Note that pooling is not enabled for such connections, because "Stop TLS" is not performed.
        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
        env.put(Context.PROVIDER_URL, providerUrl);
        env.put(Context.REFERRAL, DEFAULT_REFERRAL);
        // At this point env should not contain properties SECURITY_AUTHENTICATION, SECURITY_PRINCIPAL and SECURITY_CREDENTIALS to avoid "bind" operation prior to StartTLS:
        ctx = new InitialLdapContext(env, null);
        // http://docs.oracle.com/javase/jndi/tutorial/ldap/ext/starttls.html
        StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        try {/*w w w .j  a v a 2 s  .co  m*/
            tls.negotiate();
        } catch (IOException e) {
            NamingException ex = new NamingException("StartTLS failed");
            ex.initCause(e);
            throw ex;
        }
        // Explicitly initiate "bind" operation:
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, authentication);
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
        ctx.reconnect(null);
    } else {
        ctx = new InitialLdapContext(getEnvironment(principal, credentials, pooling), null);
    }
    return ctx;
}

From source file:org.sonar.plugins.ldap.LdapContextFactory.java

private InitialDirContext createInitialDirContextUsingGssapi(String principal, String credentials)
        throws NamingException {
    Configuration.setConfiguration(new Krb5LoginConfiguration());
    InitialDirContext initialDirContext;
    try {/*from  w w  w  . j a  va 2  s . c om*/
        LoginContext lc = new LoginContext(getClass().getName(),
                new CallbackHandlerImpl(principal, credentials));
        lc.login();
        initialDirContext = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<InitialDirContext>() {
            @Override
            public InitialDirContext run() throws NamingException {
                Properties env = new Properties();
                env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
                env.put(Context.PROVIDER_URL, providerUrl);
                env.put(Context.REFERRAL, DEFAULT_REFERRAL);
                return new InitialLdapContext(env, null);
            }
        });
    } catch (LoginException | PrivilegedActionException e) {
        NamingException namingException = new NamingException(e.getMessage());
        namingException.initCause(e);
        throw namingException;
    }
    return initialDirContext;
}

From source file:org.sonatype.security.ldap.realms.DefaultLdapContextFactory.java

public LdapContext getLdapContext(String username, String password, boolean systemContext)
        throws NamingException {
    return new InitialLdapContext(getSetupEnvironment(username, password, systemContext), null);
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPConnectionContext.java

/**
 * @param userDN Distinguished name of the user to be authenticated
 * @param password Password of the user to be authenticated
 * @return The LDAP connection context with logged in as the given user.
 * @throws NamingException If the user cannot be authenticated or connection issue occurs.
 *///from   www .j  av a 2 s .  c o m
LdapContext getContextWithCredentials(String userDN, String password) throws NamingException {
    LdapContext context;

    //create a temp env for this particular authentication session by copying the original env
    Hashtable<String, String> tempEnv = new Hashtable<>();
    for (Map.Entry<String, String> entry : environment.entrySet()) {
        tempEnv.put(entry.getKey(), entry.getValue());
    }
    //replace connection name and password with the passed credentials to this method
    tempEnv.put(Context.SECURITY_PRINCIPAL, userDN);
    tempEnv.put(Context.SECURITY_CREDENTIALS, password);

    //replace environment properties with these credentials
    context = new InitialLdapContext(tempEnv, null);
    return (context);
}

From source file:org.wso2.carbon.user.core.ldap.LDAPConnectionContext.java

public LdapContext getContextWithCredentials(String userDN, String password)
        throws UserStoreException, NamingException, AuthenticationException {
    LdapContext context = null;// ww  w .  j  av a 2s.  co  m

    //create a temp env for this particular authentication session by copying the original env
    Hashtable<String, String> tempEnv = new Hashtable<String, String>();
    for (Object key : environment.keySet()) {
        tempEnv.put((String) key, (String) environment.get(key));
    }
    //replace connection name and password with the passed credentials to this method
    tempEnv.put(Context.SECURITY_PRINCIPAL, userDN);
    tempEnv.put(Context.SECURITY_CREDENTIALS, password);

    //if dcMap is not populated, it is not DNS case
    if (dcMap == null) {

        //replace environment properties with these credentials
        context = new InitialLdapContext(tempEnv, null);

    } else if (dcMap != null && dcMap.size() != 0) {
        try {
            //first try the first entry in dcMap, if it fails, try iteratively
            Integer firstKey = dcMap.firstKey();
            SRVRecord firstRecord = dcMap.get(firstKey);
            //compose the connection URL
            tempEnv.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(firstRecord));
            context = new InitialLdapContext(tempEnv, null);

        } catch (AuthenticationException e) {
            throw e;

        } catch (NamingException e) {
            log.error("Error obtaining connection to first Domain Controller." + e.getMessage(), e);
            log.info("Trying to connect with other Domain Controllers");

            for (Integer integer : dcMap.keySet()) {
                try {
                    SRVRecord srv = dcMap.get(integer);
                    environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(srv));
                    context = new InitialLdapContext(environment, null);
                    break;
                } catch (AuthenticationException e2) {
                    throw e2;
                } catch (NamingException e1) {
                    if (integer == (dcMap.lastKey())) {
                        log.error("Error obtaining connection for all " + integer + " Domain Controllers."
                                + e1.getMessage(), e1);
                        throw new UserStoreException("Error obtaining connection. " + e1.getMessage(), e1);
                    }
                }
            }
        }
    }
    return (context);
}