Example usage for javax.naming.directory SearchResult getNameInNamespace

List of usage examples for javax.naming.directory SearchResult getNameInNamespace

Introduction

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

Prototype

public String getNameInNamespace() 

Source Link

Document

Retrieves the full name of this binding.

Usage

From source file:ldap.Entry.java

public Entry(SearchResult result) throws InvalidNameException {
    this(new LdapName(result.getNameInNamespace()), result.getAttributes());
}

From source file:com.adito.activedirectory.PagedResultTemplate.java

private void mapResults(PagedResultMapper mapper, NamingEnumeration<SearchResult> results)
        throws NamingException {
    while (results != null && results.hasMore()) {
        SearchResult searchResult = results.next();
        String dn = searchResult.getNameInNamespace();

        try {//from  w  w  w  .  j  a v  a 2s.  c o  m
            if (isDnValid(dn)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Included result " + dn);
                }
                mapper.mapSearchResult(searchResult);
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Excluding result " + dn);
                }
            }
        } catch (Exception e) {
            mapper.processSearchResultException(searchResult, e);
        }
    }
}

From source file:org.codehaus.plexus.redback.authentication.ldap.LdapBindAuthenticator.java

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

    if (!config.getBoolean("ldap.bind.authenticator.enabled")
            || (!config.getBoolean("ldap.bind.authenticator.allowEmptyPasswords", false)
                    && StringUtils.isEmpty(source.getPassword()))) {
        return new AuthenticationResult(false, source.getPrincipal(), null);
    }//from   w ww .jav a2s . co  m

    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.getPrincipal() + "))";

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

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

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

            DirContext context = ldapConnection.getDirContext();

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

            log.info("Found user?: {}", results.hasMoreElements());

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

                userDn = result.getNameInNamespace();

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

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

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

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

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

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);
    }//  w  w w  .j  a  v  a2 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:org.archone.ad.authentication.ShoadRealm.java

private String getUserDn(String username) throws javax.naming.NamingException {
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    DirContext dirContext = contextSource.getReadOnlyContext();
    NamingEnumeration<SearchResult> searchResults = dirContext.search("",
            adConfiguration.getUserDnSearchFilter(), new String[] { username }, controls);

    SearchResult sr = searchResults.next();

    if (sr == null || searchResults.hasMore()) {
        throw new AuthenticationException();
    }/*from  w  w  w. j  a  va 2 s . c  om*/

    return sr.getNameInNamespace();
}

From source file:io.lavagna.service.Ldap.java

public Pair<Boolean, List<String>> authenticateWithParams(String providerUrl, String ldapManagerDn,
        String ldapManagerPwd, String base, String filter, String username, String password) {
    requireNonNull(username);/*w ww. j  av  a 2s .c om*/
    requireNonNull(password);
    List<String> msgs = new ArrayList<>();

    msgs.add(format("connecting to %s with managerDn %s", providerUrl, ldapManagerDn));
    try (InitialDirContextCloseable dctx = ldapConnection.context(providerUrl, ldapManagerDn, ldapManagerPwd)) {
        msgs.add(format("connected [ok]"));
        msgs.add(format("now searching user \"%s\" with base %s and filter %s", username, base, filter));

        SearchControls sc = new SearchControls();
        sc.setReturningAttributes(null);
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

        List<SearchResult> srs = Ldap.search(dctx, base,
                new MessageFormat(filter).format(new Object[] { Ldap.escapeLDAPSearchFilter(username) }), sc);
        if (srs.size() != 1) {
            String msg = format("error for username \"%s\" we have %d results instead of 1 [error]", username,
                    srs.size());
            msgs.add(msg);
            LOG.info(msg, username, srs.size());
            return Pair.Companion.of(false, msgs);
        }

        msgs.add("user found, now will connect with given password [ok]");

        SearchResult sr = srs.get(0);

        try (InitialDirContextCloseable uctx = ldapConnection.context(providerUrl, sr.getNameInNamespace(),
                password)) {
            msgs.add("user authenticated, everything seems ok [ok]");
            return Pair.Companion.of(true, msgs);
        } catch (NamingException e) {
            String msg = format("error while checking with username \"%s\" with message: %s [error]", username,
                    e.getMessage());
            msgs.add(msg);
            LOG.info(msg, e);
            return Pair.Companion.of(false, msgs);
        }
    } catch (Throwable e) {
        String errMsg = format(
                "error while opening the connection with message: %s [error], check the logs for a more complete trace",
                e.getMessage());
        msgs.add(errMsg);
        msgs.add("Full stacktrace is:");
        msgs.add(ExceptionUtils.getStackTrace(e));
        LOG.error(errMsg, e);
        return Pair.Companion.of(false, msgs);
    }
}

From source file:net.officefloor.plugin.web.http.security.store.JndiLdapCredentialStore.java

@Override
public CredentialEntry retrieveCredentialEntry(String userId, String realm) throws IOException {
    try {/*  w  w w .  ja  v  a  2s.c  o m*/
        // Search for the credential entry
        NamingEnumeration<SearchResult> searchResults = this.context.search(this.entrySearchBaseDn,
                "(&(objectClass=inetOrgPerson)(uid=" + userId + "))", null);
        if (!searchResults.hasMore()) {
            return null; // entry not found
        }
        SearchResult result = searchResults.next();

        // Obtain the attributes
        String entryDn = result.getNameInNamespace();

        // Create and return the credential entry
        return new JndiLdapCredentialEntry(entryDn);

    } catch (NamingException ex) {
        throw new IOException(ex);
    }
}

From source file:com.teklabs.throng.integration.ldap.Ldap.java

private String getPrincipal(String login) throws NamingException {
    if (baseDN == null) {
        throw new IllegalArgumentException("LDAP BaseDN is not set");
    }/*from  w ww.  ja  v a2s .c om*/
    InitialDirContext context = null;
    String principal;
    try {
        if (LdapHelper.LOG.isDebugEnabled()) {
            LdapHelper.LOG.debug("Search principal: " + login);
        }

        context = ldapContextFactory.getInitialDirContext();
        String request = "(&(objectClass=" + userObjectClass + ")(" + loginAttribute + "={0}))";
        if (LdapHelper.LOG.isDebugEnabled()) {
            LdapHelper.LOG.debug("LDAP request: " + request);
        }

        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        controls.setReturningAttributes(new String[] {});
        controls.setReturningObjFlag(true);
        NamingEnumeration result = context.search(baseDN, request, new String[] { login }, controls);
        String found = null;
        if (result.hasMore()) {
            SearchResult obj = (SearchResult) result.next();
            found = obj.getNameInNamespace();
            if (found != null && result.hasMore()) {
                found = null;
                LdapHelper.LOG.error(
                        "Login \'" + login + "\' is not unique in LDAP (see attribute " + loginAttribute + ")");
            }
        }

        principal = found;
    } finally {
        LdapHelper.closeContext(context);
    }

    return principal;
}

From source file:org.wso2.carbon.appfactory.userstore.AppFactoryTenantManager.java

protected String[] getTenantDomains(String userDN) throws UserStoreException {
    DirContext dirContext;/*from   w  w  w  .j  a  va 2 s  . c om*/
    String groupNameSearchFilter = realmConfig.getUserStoreProperty("GroupNameListFilter");
    String groupNameProperty = realmConfig.getUserStoreProperty("MembershipAttribute");
    String searchFilter = getSearchFilter(groupNameSearchFilter, groupNameProperty, userDN);
    Set<String> list = new HashSet<String>();
    if (log.isDebugEnabled()) {
        log.debug((new StringBuilder()).append("Searching for ").append(searchFilter).toString());
    }
    dirContext = ldapConnectionSource.getContext();
    NamingEnumeration answer = null;
    String domainsStrs[];
    try {
        String dn;
        String domain;
        answer = searchForObject(searchFilter, null, dirContext,
                tenantMgtConfig.getTenantStoreProperties().get("RootPartition"));
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult) answer.next();
            dn = sr.getNameInNamespace();
            domain = getOrganizationalContextName(dn);
            if (domain != null) {
                list.add(domain);
            }
        }

        domainsStrs = list.toArray(new String[list.size()]);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }

    return domainsStrs;

}

From source file:alpine.auth.LdapConnectionWrapper.java

/**
 * Retrieves a list of all the groups in the directory.
 * @param dirContext a DirContext// w  ww .  ja  v a  2 s. c  o m
 * @return A list of Strings representing the fully qualified DN of each group
 * @throws NamingException if an exception if thrown
 * @since 1.4.0
 */
public List<String> getGroups(DirContext dirContext) throws NamingException {
    final List<String> groupDns = new ArrayList<>();
    final SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final NamingEnumeration<SearchResult> ne = dirContext.search(BASE_DN, GROUPS_FILTER, sc);
    while (hasMoreEnum(ne)) {
        final SearchResult result = ne.next();
        groupDns.add(result.getNameInNamespace());
    }
    closeQuietly(ne);
    return groupDns;
}