Example usage for javax.naming.directory SearchControls SearchControls

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

Introduction

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

Prototype

public SearchControls() 

Source Link

Document

Constructs a search constraints using defaults.

Usage

From source file:org.springframework.ldap.pool.validation.DefaultDirContextValidator.java

/**
 * Create a validator with all the defaults of the default constructor, but with the search scope set to the
 * referred value./*  w w w  .j  a  v a2s  .c o m*/
 *
 * @param searchScope The searchScope to be set in the default <code>SearchControls</code>
 */
public DefaultDirContextValidator(int searchScope) {
    this.searchControls = new SearchControls();
    this.searchControls.setSearchScope(searchScope);
    this.searchControls.setCountLimit(1);
    this.searchControls.setReturningAttributes(new String[] { "objectclass" });
    this.searchControls.setTimeLimit(500);

    this.base = "";

    this.filter = "objectclass=*";
}

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

public boolean authenticateUser(String userLogin, UserEdit edit, String password) {
    Hashtable env = new Hashtable();
    InitialDirContext ctx;//  w w  w .  j  av  a2s  . c  o  m

    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: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  www .j  a  v a 2  s  .  com

    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: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   www  .  ja v  a  2  s  . c  o m*/
    }

    return searchResult;
}

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.
 * /*from  w  ww. j  a  v  a2s. c om*/
 * @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.nuxeo.ecm.directory.ldap.ExternalLDAPDirectoryFeature.java

protected void destroyRecursively(String dn, DirContext ctx, int limit) throws NamingException {
    if (limit == 0) {
        log.warn("Reach recursion limit, stopping deletion at" + dn);
        return;/*from w w  w  .  j  a  v  a 2  s  .co m*/
    }
    SearchControls scts = new SearchControls();
    scts.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    NamingEnumeration<SearchResult> children = ctx.search(dn, "(objectClass=*)", scts);
    try {
        while (children.hasMore()) {
            SearchResult child = children.next();
            String subDn = child.getName();

            subDn = subDn + ',' + dn;
            destroyRecursively(subDn, ctx, limit);
        }
    } catch (SizeLimitExceededException e) {
        log.warn("SizeLimitExceededException: trying again on partial results " + dn);
        if (limit == -1) {
            limit = 100;
        }
        destroyRecursively(dn, ctx, limit - 1);
    }
    ctx.destroySubcontext(dn);
}

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  ava2s . com*/
        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:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java

/**
 * Note that {@link User.getPassword()} will not give the password from the repository after 'unmarshalling'.
 * The user repository must be queried for this because the password is never retrieved from the repository 
 * and the User object does not contain it.  
 * /*  w  ww  .ja v a  2s .c o  m*/
 */
public boolean isPasswordStored(String userId) throws RepositoryException {
    if (StringUtils.isBlank(userId)) {
        logger.debug("Insufficient data for getting user info.");
        throw new IllegalArgumentException();
    }
    String filter = "(&(objectClass=" + getObjectClassName() + ")(uid=" + userId + "))";

    final String PASSWD_ATTR_NAME = "userPassword";
    boolean passwordStored = false;
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setCountLimit(1);
    ctls.setReturningAttributes(new String[] { "uid", PASSWD_ATTR_NAME });

    try {
        NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls);
        while (resultEnum.hasMoreElements()) {
            SearchResult result = resultEnum.next();
            Attributes attrs = result.getAttributes();
            if (attrs.get(PASSWD_ATTR_NAME) != null)
                passwordStored = true;
        }
    } catch (NamingException e) {
        throw new RepositoryException(e);
    }

    return passwordStored;
}

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.
 * /*from   ww w .  ja v a  2 s. co m*/
 * @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;
}