Example usage for javax.naming.directory SearchControls SUBTREE_SCOPE

List of usage examples for javax.naming.directory SearchControls SUBTREE_SCOPE

Introduction

In this page you can find the example usage for javax.naming.directory SearchControls SUBTREE_SCOPE.

Prototype

int SUBTREE_SCOPE

To view the source code for javax.naming.directory SearchControls SUBTREE_SCOPE.

Click Source Link

Document

Search the entire subtree rooted at the named object.

Usage

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

public boolean authenticateUser(String userLogin, UserEdit edit, String password) {
    Hashtable env = new Hashtable();
    InitialDirContext ctx;/*from  w ww. j  a  va  2s.  c om*/

    String INIT_CTX = "com.sun.jndi.ldap.LdapCtxFactory";
    String MY_HOST = getLdapHost() + ":" + getLdapPort();
    String cn;
    boolean returnVal = false;

    if (!password.equals("")) {

        env.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
        env.put(Context.PROVIDER_URL, MY_HOST);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_CREDENTIALS, "secret");

        String[] returnAttribute = { "ou" };
        SearchControls srchControls = new SearchControls();
        srchControls.setReturningAttributes(returnAttribute);
        srchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(userLogin) + "))";

        try {
            ctx = new InitialDirContext(env);
            NamingEnumeration answer = ctx.search(getBasePath(), searchFilter, srchControls);
            String trobat = "false";

            while (answer.hasMore() && trobat.equals("false")) {

                SearchResult sr = (SearchResult) answer.next();
                String dn = sr.getName().toString() + "," + getBasePath();

                // Second binding
                Hashtable authEnv = new Hashtable();
                try {
                    authEnv.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
                    authEnv.put(Context.PROVIDER_URL, MY_HOST);
                    authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
                    authEnv.put(Context.SECURITY_PRINCIPAL, sr.getName() + "," + getBasePath());
                    authEnv.put(Context.SECURITY_CREDENTIALS, password);
                    try {
                        DirContext authContext = new InitialDirContext(authEnv);
                        returnVal = true;
                        trobat = "true";
                        authContext.close();
                    } catch (AuthenticationException ae) {
                        M_log.info("Access forbidden");
                    }

                } catch (NamingException namEx) {
                    M_log.info("User doesn't exist");
                    returnVal = false;
                    namEx.printStackTrace();
                }
            }
            if (trobat.equals("false"))
                returnVal = false;

        } catch (NamingException namEx) {
            namEx.printStackTrace();
            returnVal = false;
        }
    }
    return returnVal;
}

From source file:com.marklogic.samplestack.integration.web.LDAPIT.java

private SearchResult findAccountByAccountName(String accountName) throws NamingException {

    String searchFilter = "(&(objectclass=person)(cn=" + accountName + "))";

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls);

    SearchResult searchResult = null;
    if (results.hasMoreElements()) {
        searchResult = (SearchResult) results.nextElement();

        // make sure there is not another item available, there should be
        // only 1 match
        if (results.hasMoreElements()) {
            System.err.println("Matched multiple users for the accountName: " + accountName);
            return null;
        }//from w  w  w  .  ja v  a 2s .com
    }

    return searchResult;
}

From source file:org.apache.archiva.redback.authentication.ldap.LdapBindAuthenticator.java

public AuthenticationResult authenticate(AuthenticationDataSource s) throws AuthenticationException {
    PasswordBasedAuthenticationDataSource source = (PasswordBasedAuthenticationDataSource) s;

    if (!config.getBoolean(UserConfigurationKeys.LDAP_BIND_AUTHENTICATOR_ENABLED)
            || (!config.getBoolean(UserConfigurationKeys.LDAP_BIND_AUTHENTICATOR_ALLOW_EMPTY_PASSWORDS, false)
                    && StringUtils.isEmpty(source.getPassword()))) {
        return new AuthenticationResult(false, source.getUsername(), null);
    }/*from  w  ww . j a  v  a2 s .  c  om*/

    SearchControls ctls = new SearchControls();

    ctls.setCountLimit(1);

    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = "(&(objectClass=" + mapper.getUserObjectClass() + ")"
            + (mapper.getUserFilter() != null ? mapper.getUserFilter() : "") + "(" + mapper.getUserIdAttribute()
            + "=" + source.getUsername() + "))";

    log.debug("Searching for users with filter: '{}' from base dn: {}", filter, mapper.getUserBaseDn());

    LdapConnection ldapConnection = null;
    LdapConnection authLdapConnection = null;
    NamingEnumeration<SearchResult> results = null;
    try {
        ldapConnection = getLdapConnection();
        // check the cache for user's userDn in the ldap server
        String userDn = ldapCacheService.getLdapUserDn(source.getUsername());

        if (userDn == null) {
            log.debug("userDn for user {} not found in cache. Retrieving from ldap server..",
                    source.getUsername());

            DirContext context = ldapConnection.getDirContext();

            results = context.search(mapper.getUserBaseDn(), filter, ctls);

            log.debug("Found user '{}': {}", source.getUsername(), results.hasMoreElements());

            if (results.hasMoreElements()) {
                SearchResult result = results.nextElement();

                userDn = result.getNameInNamespace();

                log.debug("Adding userDn {} for user {} to the cache..", userDn, source.getUsername());

                // REDBACK-289/MRM-1488 cache the ldap user's userDn to lessen calls to ldap server
                ldapCacheService.addLdapUserDn(source.getUsername(), userDn);
            } else {
                return new AuthenticationResult(false, source.getUsername(), null);
            }
        }

        log.debug("Attempting Authenication: {}", userDn);

        authLdapConnection = connectionFactory.getConnection(userDn, source.getPassword());

        log.info("user '{}' authenticated", source.getUsername());

        return new AuthenticationResult(true, source.getUsername(), null);
    } catch (LdapException e) {
        return new AuthenticationResult(false, source.getUsername(), e);
    } catch (NamingException e) {
        return new AuthenticationResult(false, source.getUsername(), e);
    } finally {
        closeNamingEnumeration(results);
        closeLdapConnection(ldapConnection);
        if (authLdapConnection != null) {
            closeLdapConnection(authLdapConnection);
        }
    }
}

From source file:net.identio.server.service.authentication.ldap.LdapAuthenticationProvider.java

public AuthenticationResult validate(AuthMethod authMethod, Authentication authentication,
        TransactionData transactionData) {

    LdapAuthMethod ldapAuthMethod = (LdapAuthMethod) authMethod;
    UserPasswordAuthentication userPwAuthentication = (UserPasswordAuthentication) authentication;

    boolean validation;

    String userId = userPwAuthentication.getUserId();
    String password = userPwAuthentication.getPassword();

    GenericObjectPool<InitialLdapContext> pool = pools.get(authMethod.getName());

    InitialLdapContext ctx = null;

    try {//w  w  w . j  a v  a 2 s  .c o m
        ctx = pool.borrowObject();

        // First we search the user
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = ldapAuthMethod.getUserSearchFilter().replace("#UID",
                SecurityUtils.escapeLDAPSearchFilter(userId));

        NamingEnumeration<SearchResult> results = ctx.search(ldapAuthMethod.getBaseDn(), searchFilter,
                controls);

        SearchResult result;

        if (results.hasMoreElements()) {
            result = results.next();

            if (results.hasMoreElements()) {
                LOG.error("User ID {} is not unique in LDAP {}", userId, authMethod.getName());
                return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                        .setErrorStatus(AuthenticationErrorStatus.USER_NOT_UNIQUE);
            }
        } else {
            LOG.error("User ID {} does not exist in LDAP {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                    .setErrorStatus(AuthenticationErrorStatus.INVALID_CREDENTIALS);
        }

        // Try to bind with the found user id
        validation = ((LdapConnectionFactory) pool.getFactory()).authenticate(authMethod.getName(),
                result.getNameInNamespace(), password);

        pool.returnObject(ctx);

        if (validation) {
            LOG.info("User {} successfully authenticated with {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.SUCCESS).setUserId(userId)
                    .setAuthMethod(authMethod).setAuthLevel(authMethod.getAuthLevel());
        } else {
            LOG.error("Authentication failed for user {} with {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                    .setErrorStatus(AuthenticationErrorStatus.INVALID_CREDENTIALS);
        }

    } catch (Exception ex) {

        // Discard context
        try {
            if (ctx != null) {
                pool.invalidateObject(ctx);
            }
        } catch (Exception ex2) {
            LOG.error("An error occurend when authenticating user");
        }

        return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                .setErrorStatus(AuthenticationErrorStatus.TECHNICAL_ERROR);
    }

}

From source file:org.jkcsoft.java.util.JndiHelper.java

public static Map getUserInfo(BehavioralContext ctx, String userName) throws NamingException {
    Map infoMap = null;//from   ww w . j  a  v a  2  s  .  c om

    Configuration cfg = ctx.getConfig();
    // 
    String searchRelativeDc = cfg.getString(Constants.KEY_AD_USER_NODE_DN);
    String theFilter = LDAP_USER_SAMACCOUNTNAME + "=" + userName;
    List theAttrsList = new Vector(Arrays.asList(ldapUserAttrs));
    theAttrsList.addAll(Arrays.asList(ldapTopAttrs));

    int countLimit = 1000;
    int timeLimitMillis = 30000;
    boolean returnObject = false;
    boolean derefObj = true;

    SearchControls scs = new SearchControls(SearchControls.SUBTREE_SCOPE, countLimit, timeLimitMillis,
            (String[]) theAttrsList.toArray(new String[0]), returnObject, derefObj);

    DirContext rootCtx = getTsessAccountContext(ctx);

    try {
        log.debug("Search params name[" + searchRelativeDc + "] " + "filter[" + theFilter + "] controls[" + scs
                + "]");

        NamingEnumeration results = rootCtx.search(searchRelativeDc, theFilter, scs);

        if (results == null || !results.hasMore())
            throw new NamingException("User LDAP entry not found");

        SearchResult searchResult = ((SearchResult) results.next());
        if (searchResult == null)
            throw new NamingException("User LDAP entry not found");

        if (log.isTraceEnabled()) {
            logLdap(log, 0, 0, searchResult);
        }

        Attributes userLdapAttrs = searchResult.getAttributes();
        infoMap = new HashMap();
        for (Iterator attrIter = theAttrsList.iterator(); attrIter.hasNext();) {
            loadMap(infoMap, userLdapAttrs, (String) attrIter.next());
        }
    } finally {
        safeClose(rootCtx);
    }

    return infoMap;
}

From source file:org.eclipselabs.etrack.util.security.ldap.impl.LdapService.java

@Override
public NamingEnumeration<SearchResult> findUser(String filter) throws NamingException {
    return find(SearchControls.SUBTREE_SCOPE, userSearchBase, userFilter + "=" + filter);
}

From source file:org.geoserver.security.ldap.GeoserverLdapBindAuthenticator.java

/**
 * If userFilter is defined we extract user data using the filter and
 * dnPattern (if defined) to transform username for authentication.
 * /*  w w  w  .  j  a  v a2  s  .  c om*/
 * @param authentication
 * @return
 */
protected DirContextOperations authenticateUsingFilter(Authentication authentication) {
    DirContextOperations user = null;
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            "Can only process UsernamePasswordAuthenticationToken objects");

    String username = authentication.getName();
    String password = (String) authentication.getCredentials();
    // format given username if required
    if (userFormat != null && !userFormat.equals("")) {
        username = MessageFormat.format(userFormat, username);
    }
    if (!StringUtils.hasLength(password)) {
        logger.debug("Rejecting empty password for user " + username);
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.emptyPassword", "Empty Password"));
    }

    DirContext ctx = null;
    String userDnStr = "";
    try {
        ctx = getContextSource().getContext(username, password);

        // Check for password policy control
        PasswordPolicyControl ppolicy = PasswordPolicyControlExtractor.extractControl(ctx);

        logger.debug("Retrieving user object using filter...");
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        user = SpringSecurityLdapTemplate.searchForSingleEntryInternal(ctx, searchCtls, "", userFilter,
                new Object[] { username });
        userDnStr = user.getDn().toString();
        if (ppolicy != null) {
            user.setAttributeValue(ppolicy.getID(), ppolicy);
        }

    } catch (NamingException e) {
        // This will be thrown if an invalid user name is used and the
        // method may
        // be called multiple times to try different names, so we trap the
        // exception
        // unless a subclass wishes to implement more specialized behaviour.
        if ((e instanceof org.springframework.ldap.AuthenticationException)
                || (e instanceof org.springframework.ldap.OperationNotSupportedException)) {
            handleBindException(userDnStr, username, e);
        } else {
            throw e;
        }
    } catch (javax.naming.NamingException e) {
        throw LdapUtils.convertLdapException(e);
    } finally {
        LdapUtils.closeContext(ctx);
    }

    if (user == null) {
        throw new BadCredentialsException(
                messages.getMessage("BindAuthenticator.badCredentials", "Bad credentials"));
    }

    return user;
}

From source file:org.eurekastreams.server.persistence.mappers.ldap.LdapLookup.java

/**
 * Execute an ldap query based on {@link LdapLookupRequest} parameters and this DAO's configuration.
 * LdapLookupRequest is used for search upper bound, the {@link LdapTemplate}, and the search string. The rest of
 * ldap query functionality is determined by DAO configuration.
 * //  w w  w  .  jav  a 2s.c o m
 * @param inRequest
 *            {@link LdapLookupRequest}.
 * @return List of objects found as as result of ldap query.
 * 
 */
@Override
public List<Type> execute(final LdapLookupRequest inRequest) {
    // get ldap template.
    LdapTemplate template = ldapTemplateRetriever.getLdapTemplate(inRequest);

    // set up search controls.
    SearchControls searchControls = new SearchControls();
    searchControls.setCountLimit(inRequest.getSearchUpperBound());
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // add passed in attribute criteria to filter.
    AbstractFilter abstractFilter = filterCreator.getFilter(inRequest.getQueryString());

    // get the configured CollectingNameClassPairCallbackHandler to use for query.
    CollectingNameClassPairCallbackHandler collectingHandler = handlerFactory.getCallbackHandler();

    // execute query.
    ldapSearchStrategy.searchLdap(template, abstractFilter.encode(), searchControls, collectingHandler);

    // get results gathered by CollectingNameClassPairCallbackHandler.
    List<Type> rawResults = collectingHandler.getList();

    // Results contain nulls if the context/attribute mappers were unable to create objects, so pull them out.
    List<Type> results = new ArrayList<Type>();
    for (Type t : rawResults) {
        if (t != null) {
            results.add(t);
        }
    }

    return results;
}

From source file:org.jasig.cas.adaptors.ldap.services.LdapServiceRegistryDao.java

protected String findDn(final String filter) {
    final List results = this.ldapTemplate.search(this.serviceBaseDn, filter, SearchControls.SUBTREE_SCOPE,
            new String[0], new ContextMapper() {
                public Object mapFromContext(final Object ctx) {
                    return ((DirContextAdapter) ctx).getNameInNamespace();
                }/* w  ww .  java 2 s.  c o  m*/
            });
    if (results == null || results.isEmpty()) {
        return null;
    } else if (results.size() == 1 || this.ignoreMultipleSearchResults) {
        return (String) results.get(0);
    } else {
        throw new RuntimeException("Multiple results returned by LDAP Server for Filter " + filter);
    }
}