Search in sources :

Example 1 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project neo4j by neo4j.

the class LdapRealm method getLdapContextUsingStartTls.

private LdapContext getLdapContextUsingStartTls(LdapContextFactory ldapContextFactory, Object principal, Object credentials) throws NamingException {
    JndiLdapContextFactory jndiLdapContextFactory = (JndiLdapContextFactory) ldapContextFactory;
    Hashtable<String, Object> env = new Hashtable<>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, jndiLdapContextFactory.getContextFactoryClassName());
    env.put(Context.PROVIDER_URL, jndiLdapContextFactory.getUrl());
    LdapContext ctx = null;
    try {
        ctx = new InitialLdapContext(env, null);
        StartTlsRequest startTlsRequest = new StartTlsRequest();
        StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(startTlsRequest);
        tls.negotiate();
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, jndiLdapContextFactory.getAuthenticationMechanism());
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
        ctx.reconnect(ctx.getConnectControls());
        return ctx;
    } catch (IOException e) {
        LdapUtils.closeContext(ctx);
        securityLog.error(withRealm("Failed to negotiate TLS connection with '%s': ", server(jndiLdapContextFactory), e));
        throw new CommunicationException(e.getMessage());
    } catch (Throwable t) {
        LdapUtils.closeContext(ctx);
        securityLog.error(withRealm("Unexpected failure to negotiate TLS connection with '%s': ", server(jndiLdapContextFactory), t));
        throw t;
    }
}
Also used : StartTlsResponse(javax.naming.ldap.StartTlsResponse) CommunicationException(javax.naming.CommunicationException) Hashtable(java.util.Hashtable) InitialLdapContext(javax.naming.ldap.InitialLdapContext) IOException(java.io.IOException) StartTlsRequest(javax.naming.ldap.StartTlsRequest) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext) JndiLdapContextFactory(org.apache.shiro.realm.ldap.JndiLdapContextFactory)

Example 2 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project wildfly by wildfly.

the class LdapUrlTestServlet method runSearch.

/**
     * Try to search in LDAP with search base containing URL. Also try to retrieve RequestControls from LdapContext.
     *
     * @param hostname
     * @return
     * @throws Exception
     */
public static String runSearch(final String hostname, boolean testLdapCtx) throws Exception {
    final StringBuilder result = new StringBuilder();
    final String ldapUrl = "ldap://" + (hostname == null ? "localhost" : hostname) + ":10389";
    final Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    final SearchControls ctl = new SearchControls();
    ctl.setReturningAttributes(new String[] { "cn" });
    DirContext dirCtx = null;
    if (testLdapCtx) {
        // LdapContext must also work
        LdapContext ldapCtx = new InitialLdapContext(env, null);
        // next line tests if the LdapContext works
        ldapCtx.getRequestControls();
        dirCtx = ldapCtx;
    } else {
        dirCtx = new InitialDirContext(env);
    }
    final NamingEnumeration<SearchResult> nenum = dirCtx.search(ldapUrl + "/dc=jboss,dc=org", "(uid=jduke)", ctl);
    while (nenum.hasMore()) {
        SearchResult sr = nenum.next();
        Attributes attrs = sr.getAttributes();
        result.append("cn=").append(attrs.get("cn").get());
    }
    dirCtx.close();
    return result.toString();
}
Also used : Hashtable(java.util.Hashtable) InitialLdapContext(javax.naming.ldap.InitialLdapContext) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext)

Example 3 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project ranger by apache.

the class UserInfo method createLdapContext.

private void createLdapContext() throws Throwable {
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    if (ldapUrl.startsWith("ldaps") && (config.getSSLTrustStorePath() != null && !config.getSSLTrustStorePath().trim().isEmpty())) {
        env.put("java.naming.ldap.factory.socket", "org.apache.ranger.ldapusersync.process.CustomSSLSocketFactory");
    }
    ldapContext = new InitialLdapContext(env, null);
    if (!ldapUrl.startsWith("ldaps")) {
        if (config.isStartTlsEnabled()) {
            tls = (StartTlsResponse) ldapContext.extendedOperation(new StartTlsRequest());
            if (config.getSSLTrustStorePath() != null && !config.getSSLTrustStorePath().trim().isEmpty()) {
                tls.negotiate(CustomSSLSocketFactory.getDefault());
            } else {
                tls.negotiate();
            }
            LOG.info("Starting TLS session...");
        }
    }
    ldapContext.addToEnvironment(Context.SECURITY_PRINCIPAL, ldapBindDn);
    ldapContext.addToEnvironment(Context.SECURITY_CREDENTIALS, ldapBindPassword);
    ldapContext.addToEnvironment(Context.SECURITY_AUTHENTICATION, ldapAuthenticationMechanism);
    ldapContext.addToEnvironment(Context.REFERRAL, ldapReferral);
}
Also used : InitialLdapContext(javax.naming.ldap.InitialLdapContext) Properties(java.util.Properties) StartTlsRequest(javax.naming.ldap.StartTlsRequest)

Example 4 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project uavstack by uavorg.

the class GUISSOLdapClient method initLdapContext.

private void initLdapContext(String action) {
    if (!ldapContexts.containsKey(action)) {
        try {
            loggerInfo("LDAPContext", "初始化", "开始", action);
            initLdapParams(action);
            Properties actionParam = ldapParams.get(action);
            LdapContext newContext = new InitialLdapContext(actionParam, null);
            ldapContexts.put(action, newContext);
            loggerInfo("LDAPContext", "初始化", "完成", action);
        } catch (Exception e) {
            loggerError("LDAPContext初始化", action, e);
        }
    }
}
Also used : InitialLdapContext(javax.naming.ldap.InitialLdapContext) Properties(java.util.Properties) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext) ApphubException(com.creditease.uav.exception.ApphubException) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException)

Example 5 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project Lucee by lucee.

the class LDAPClient method query.

/**
 * @param dn
 * @param strAttributes
 * @param scope
 * @param startrow
 * @param maxrows
 * @param timeout
 * @param sort
 * @param sortType
 * @param sortDirection
 * @param start
 * @param separator
 * @param filter
 * @return
 * @throws NamingException
 * @throws PageException
 * @throws IOException
 */
public Query query(String strAttributes, int scope, int startrow, int maxrows, int timeout, String[] sort, int sortType, int sortDirection, String start, String separator, String filter) throws NamingException, PageException, IOException {
    // strAttributes=strAttributes.trim();
    boolean attEQAsterix = strAttributes.trim().equals("*");
    String[] attributes = attEQAsterix ? new String[] { "name", "value" } : toStringAttributes(strAttributes, ",");
    // Control
    SearchControls controls = new SearchControls();
    controls.setReturningObjFlag(true);
    controls.setSearchScope(scope);
    if (!attEQAsterix)
        controls.setReturningAttributes(toStringAttributes(strAttributes, ","));
    if (maxrows > 0)
        controls.setCountLimit(startrow + maxrows + 1);
    if (timeout > 0)
        controls.setTimeLimit(timeout);
    InitialLdapContext context = new InitialLdapContext(env, null);
    // Search
    Query qry = new QueryImpl(attributes, 0, "query");
    try {
        NamingEnumeration results = context.search(start, filter, controls);
        // Fill result
        int row = 1;
        if (!attEQAsterix) {
            while (results.hasMoreElements()) {
                SearchResult resultRow = (SearchResult) results.next();
                if (row++ < startrow)
                    continue;
                int len = qry.addRow();
                NamingEnumeration rowEnum = resultRow.getAttributes().getAll();
                String dn = resultRow.getNameInNamespace();
                qry.setAtEL("dn", len, dn);
                while (rowEnum.hasMore()) {
                    Attribute attr = (Attribute) rowEnum.next();
                    Collection.Key key = KeyImpl.init(attr.getID());
                    Enumeration values = attr.getAll();
                    Object value;
                    String existing, strValue;
                    while (values.hasMoreElements()) {
                        value = values.nextElement();
                        strValue = Caster.toString(value, null);
                        existing = Caster.toString(qry.getAt(key, len, null), null);
                        if (!StringUtil.isEmpty(existing) && !StringUtil.isEmpty(strValue)) {
                            value = existing + separator + strValue;
                        } else if (!StringUtil.isEmpty(existing))
                            value = existing;
                        qry.setAtEL(key, len, value);
                    }
                }
                if (maxrows > 0 && len >= maxrows)
                    break;
            }
        } else {
            outer: while (results.hasMoreElements()) {
                SearchResult resultRow = (SearchResult) results.next();
                if (row++ < startrow)
                    continue;
                Attributes attributesRow = resultRow.getAttributes();
                NamingEnumeration rowEnum = attributesRow.getIDs();
                while (rowEnum.hasMoreElements()) {
                    int len = qry.addRow();
                    String name = Caster.toString(rowEnum.next());
                    Object value = null;
                    try {
                        value = attributesRow.get(name).get();
                    } catch (Exception e) {
                    }
                    qry.setAtEL("name", len, name);
                    qry.setAtEL("value", len, value);
                    if (maxrows > 0 && len >= maxrows)
                        break outer;
                }
                qry.setAtEL("name", qry.size(), "dn");
            }
        }
    } finally {
        context.close();
    }
    // Sort
    if (sort != null && sort.length > 0) {
        int order = sortDirection == SORT_DIRECTION_ASC ? Query.ORDER_ASC : Query.ORDER_DESC;
        for (int i = sort.length - 1; i >= 0; i--) {
            String item = sort[i];
            if (item.indexOf(' ') != -1)
                item = ListUtil.first(item, " ", true);
            qry.sort(KeyImpl.getInstance(item), order);
        // keys[i] = new SortKey(item);
        }
    }
    return qry;
}
Also used : Enumeration(java.util.Enumeration) NamingEnumeration(javax.naming.NamingEnumeration) Query(lucee.runtime.type.Query) BasicAttribute(javax.naming.directory.BasicAttribute) Attribute(javax.naming.directory.Attribute) BasicAttributes(javax.naming.directory.BasicAttributes) Attributes(javax.naming.directory.Attributes) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult) ClassException(lucee.commons.lang.ClassException) NamingException(javax.naming.NamingException) PageException(lucee.runtime.exp.PageException) IOException(java.io.IOException) QueryImpl(lucee.runtime.type.QueryImpl) InitialLdapContext(javax.naming.ldap.InitialLdapContext) Collection(lucee.runtime.type.Collection) SearchControls(javax.naming.directory.SearchControls)

Aggregations

InitialLdapContext (javax.naming.ldap.InitialLdapContext)36 NamingException (javax.naming.NamingException)18 Hashtable (java.util.Hashtable)15 LdapContext (javax.naming.ldap.LdapContext)13 Attributes (javax.naming.directory.Attributes)12 Properties (java.util.Properties)9 AuthenticationException (javax.naming.AuthenticationException)8 BasicAttributes (javax.naming.directory.BasicAttributes)8 SearchResult (javax.naming.directory.SearchResult)8 LdapConfigProperties (org.bedework.calfacade.configs.LdapConfigProperties)8 CalFacadeException (org.bedework.calfacade.exc.CalFacadeException)8 IOException (java.io.IOException)7 NamingEnumeration (javax.naming.NamingEnumeration)7 Attribute (javax.naming.directory.Attribute)7 StartTlsRequest (javax.naming.ldap.StartTlsRequest)7 BwGroup (org.bedework.calfacade.BwGroup)6 CommunicationException (javax.naming.CommunicationException)4 DirContext (javax.naming.directory.DirContext)4 ArrayList (java.util.ArrayList)3 InitialDirContext (javax.naming.directory.InitialDirContext)3