Example usage for javax.naming NamingEnumeration next

List of usage examples for javax.naming NamingEnumeration next

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration next.

Prototype

public T next() throws NamingException;

Source Link

Document

Retrieves the next element in the enumeration.

Usage

From source file:org.easy.ldap.LdapDao.java

/**
 * @param rootDn//from  w w  w.j  a  v  a  2 s  .c  o m
 * @param type
 * @return
 */
public List<String> findRdnValues(LdapName rootDn, Attributes attributesToMatch, RdnType returnType) {
    NamingEnumeration<SearchResult> result = null;
    List<String> out = new ArrayList<String>(0);

    DirContext ctx = null;

    try {
        ctx = contextFactory.createContext(rootDn.toString());
        result = ctx.search("", attributesToMatch);

        Attributes attributes;

        while (result.hasMore()) {
            attributes = result.next().getAttributes();
            out.add(attributes.get(returnType.toString()).get().toString());
        }

    } catch (NamingException e) {
        throw new RuntimeException(returnType.toString() + "," + rootDn.toString(), e);
    } finally {
        if (contextFactory != null)
            contextFactory.closeContext(ctx);
    }

    return out;
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

private boolean bindSearchX(String username, String password, Hashtable<String, String> env, boolean bind)
        throws AuthenticationException, NamingException {

    env.put(Context.SECURITY_PRINCIPAL, ldapSecurityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, ldapSecurityCredentials);

    DirContext ctx = null;/*from  ww w  . jav a 2  s . c  om*/
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException ne) {
        log.error("Failed to bind as: {}", ldapSecurityPrincipal);
    }

    // ensure we have the userPassword attribute at a minimum
    String[] attributeList = new String[] { "userPassword" };

    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(attributeList);
    sc.setDerefLinkFlag(true);
    sc.setReturningObjFlag(false);
    sc.setTimeLimit(5000);

    String filter = "(" + filterPrefix + idAttr + "=" + username + filterSuffix + ")";
    // Do the search
    NamingEnumeration<SearchResult> results = ctx.search(baseDn, filter, sc);
    if (!results.hasMore()) {
        log.warn("no valid user found.");
        return false;
    }

    SearchResult result = results.next();
    log.debug("authenticating user: {}", result.getNameInNamespace());

    if (bind) {
        // setup user context for binding
        Hashtable<String, String> userEnv = new Hashtable<String, String>();
        userEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        userEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
        userEnv.put(Context.PROVIDER_URL, baseUrl);
        userEnv.put(Context.SECURITY_PRINCIPAL, result.getNameInNamespace());
        userEnv.put(Context.SECURITY_CREDENTIALS, password);

        try {
            new InitialDirContext(userEnv);
        } catch (NamingException ne) {
            log.error("failed to authenticate user: " + result.getNameInNamespace());
            throw ne;
        }
    } else {
        // get userPassword attribute
        Attribute up = result.getAttributes().get("userPassword");
        if (up == null) {
            log.error("unable to read userPassword attribute for: {}", result.getNameInNamespace());
            return false;
        }

        byte[] userPasswordBytes = (byte[]) up.get();
        String userPassword = new String(userPasswordBytes);

        // compare passwords - also handles encodings
        if (!passwordsMatch(password, userPassword)) {
            return false;
        }
    }

    return true;
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

private Attribute getChangePasswordAttribute(Attribute oldPasswordAttribute, Object oldCredential,
        Object newPassword) throws DirectoryServerManagerException {

    String passwordHashMethod = null;
    // when admin changes other user passwords he do not have to provide
    // the old password.
    if (oldCredential != null) {
        // here it is only possible to have one password, if there are more
        // every one should match with the given old password

        try {/* ww w  .  j  ava 2  s . c  o m*/
            NamingEnumeration passwords = oldPasswordAttribute.getAll();

            if (passwords.hasMore()) {
                byte[] byteArray = (byte[]) passwords.next();
                String password = new String(byteArray, StandardCharsets.UTF_8);

                if (password.startsWith("{")) {
                    passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}"));
                }

                if (!password.equals(getPasswordToStore((String) oldCredential, passwordHashMethod))) {
                    throw new DirectoryServerManagerException("Old password does not match");
                }
            }
        } catch (NamingException e) {
            log.error("Unable to retrieve old password details.", e);
            throw new DirectoryServerManagerException("Could not find old password details");
        }
    }

    Attribute passwordAttribute = new BasicAttribute(LDAPServerManagerConstants.LDAP_PASSWORD);
    passwordAttribute.add(getPasswordToStore((String) newPassword, passwordHashMethod));

    return passwordAttribute;

}

From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java

/**
 * Gets all the user entities taken from the LDAP server, as taken from the
 * search-context given by the value of the attribute {@link #userBase}.
 *
 * @return A set containing all the relevant users found in the LDAP
 *         directory./* ww  w . ja  v a  2 s.  c o m*/
 * @throws NamingException
 *             Propagated from the LDAP communication layer.
 */
private Set<String> getAllUsersFromLDAP() throws NamingException {
    Set<String> result = new HashSet<String>();

    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { "distinguishedName" });
    NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, "(objectClass=" + userObjectClass + ")",
            sc);
    while (sr.hasMore()) {
        SearchResult r = sr.next();
        result.add(r.getNameInNamespace());
    }

    return result;
}

From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java

/**
 * For a given name, this method makes ldap search in userBase with filter {@link #userIdAttribute}=name and objectClass={@link #userObjectClass}
 * and builds {@link User} based on search result.
 *
 * @param name//  w w  w  .ja va2  s.c o  m
 *            The userId which should be value of the field {@link #userIdAttribute}
 * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the
 *         userId of this user and ldap connection information with which
 *         the user was searched. Return null if such a user was not found.
 * @throws NamingException
 *             Propagated by the underlying LDAP communication layer.
 */
private ReadOnlyLDAPUser searchAndBuildUser(String name) throws NamingException {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { userIdAttribute });
    sc.setCountLimit(1);

    StringBuilder builderFilter = new StringBuilder("(&(");
    builderFilter.append(userIdAttribute).append("=").append(name).append(")").append("(objectClass=")
            .append(userObjectClass).append(")");

    if (StringUtils.isNotEmpty(filter)) {
        builderFilter.append(filter).append(")");
    } else {
        builderFilter.append(")");
    }

    NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, builderFilter.toString(), sc);

    if (!sr.hasMore())
        return null;

    SearchResult r = sr.next();
    Attribute userName = r.getAttributes().get(userIdAttribute);

    if (!restriction.isActivated() || userInGroupsMembershipList(r.getNameInNamespace(),
            restriction.getGroupMembershipLists(ldapContext)))
        return new ReadOnlyLDAPUser(userName.get().toString(), r.getNameInNamespace(), ldapContext);

    return null;
}

From source file:ru.efo.security.ADUserDetailsService.java

private ADUserDetails loadUserByUsername(DirContext context, String username, String password)
        throws UsernameNotFoundException {
    try {/*  w ww. ja  va  2 s. c  o  m*/
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // search for username
        NamingEnumeration<SearchResult> renum = context.search(userSearchBase,
                "(&(objectClass=user)(sAMAccountName={0}))", new Object[] { username }, controls);
        if (!renum.hasMoreElements()) {
            throw new UsernameNotFoundException("User '" + username + "' is not exist");
        }
        SearchResult result = renum.next();
        final Attributes attributes = result.getAttributes();

        // User's display name
        String displayName = null;
        Attribute attr = attributes.get(displayNameAttribute);
        if (attr != null) {
            displayName = attr.get().toString();
        }
        if (!StringUtils.hasText(displayName))
            displayName = username;
        logger.log(Level.FINE, "Display name: " + displayName);

        // User's email
        String email = null;
        attr = attributes.get(emailAttribute);
        if (attr != null) {
            email = attr.get().toString();
        }
        logger.log(Level.FINE, "E-mail: " + email);

        // User's phone number
        String phone = null;
        attr = attributes.get(phoneAttribute);
        if (attr != null) {
            phone = attr.get().toString();
        }
        logger.log(Level.FINE, "Phone: " + phone);

        // Is user blocked
        boolean blocked = false;
        attr = attributes.get("userAccountControl");
        if (attr != null) {
            blocked = (Long.parseLong(attr.get().toString()) & 2) != 0;
        }
        logger.log(Level.FINE, "Blocked: " + blocked);

        // describe roles and groups
        final Set<String> roles = new TreeSet<>();
        final Set<String> groups = new TreeSet<>();
        Attribute memberOf = attributes.get("memberOf");
        describeRoles(context, memberOf, groups, roles);

        // Describe user primary role
        Attribute attrPrimaryGroupId = attributes.get("primaryGroupId");
        Attribute attrObjectSid = attributes.get("objectSid");
        if (attrPrimaryGroupId != null && attrObjectSid != null) {
            int primaryGroupId = Integer.parseInt(attrPrimaryGroupId.get().toString());
            byte[] objectSid = (byte[]) attrObjectSid.get();
            // add primary group RID
            for (int i = 0; i < 4; i++) {
                objectSid[objectSid.length - 4 + i] = (byte) (primaryGroupId & 0xFF);
                primaryGroupId >>= 8;
            }
            StringBuilder tmp = new StringBuilder();
            for (int i = 2; i <= 7; i++) {
                tmp.append(Integer.toHexString(objectSid[i] & 0xFF));
            }
            // convert objectSid to String
            StringBuilder sidBuilder = new StringBuilder("S-").append(objectSid[0]).append("-")
                    .append(Long.parseLong(tmp.toString(), 16));
            // the sub authorities count
            int count = objectSid[1];
            // add authorities
            for (int i = 0; i < count; i++) {
                tmp.setLength(0);

                int offset = i * 4;
                tmp.append(String.format("%02X%02X%02X%02X", (objectSid[11 + offset] & 0xFF),
                        (objectSid[10 + offset] & 0xFF), (objectSid[9 + offset] & 0xFF),
                        (objectSid[8 + offset] & 0xFF)));
                sidBuilder.append('-').append(Long.parseLong(tmp.toString(), 16));
            }
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            renum = context.search(userSearchBase, "(&(objectClass=group)(objectSid={0}))",
                    new Object[] { sidBuilder.toString() }, searchControls);
            if (renum.hasMoreElements()) {
                result = renum.next();
                attr = result.getAttributes().get("distinguishedName");
                describeRoles(context, attr, groups, roles);
            }
        }
        return new ADUserDetails(username, password, displayName, email, phone, blocked, groups, roles);
    } catch (NamingException ex) {
        logger.log(Level.SEVERE, "Could not find user '" + username + "'", ex);
        throw new UsernameNotFoundException(ex.getMessage());
    }
}

From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java

private String findPrincipalDN(String normalizedPrincipal) throws NamingException, KerberosOperationException {
    String dn = null;/*from ww w  .j a v a  2  s .c om*/

    if (normalizedPrincipal != null) {
        NamingEnumeration<SearchResult> results = null;

        try {
            results = ldapContext.search(principalContainerDn,
                    String.format("(userPrincipalName=%s)", normalizedPrincipal), searchControls);

            if ((results != null) && results.hasMore()) {
                SearchResult result = results.next();
                dn = result.getNameInNamespace();
            }
        } finally {
            try {
                if (results != null) {
                    results.close();
                }
            } catch (NamingException ne) {
                // ignore, we can not do anything about it
            }
        }
    }

    return dn;
}

From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * //from   ww  w. j a v a 2 s  .c  om
 * @param search
 * @param searchValue
 * @param attributeNames
 * @return attributes
 * @throws SubjectNotFoundException
 * @throws SubjectNotUniqueException
 */
protected Attributes getLdapUnique(Search search, String searchValue, String[] attributeNames)
        throws SubjectNotFoundException, SubjectNotUniqueException {
    Attributes attributes1 = null;
    NamingEnumeration results = getLdapResults(search, searchValue, attributeNames);

    try {
        if (results == null || !results.hasMore()) {
            String errMsg = "No results: " + search.getSearchType() + " filter:" + search.getParam("filter")
                    + " searchValue: " + searchValue;
            throw new SubjectNotFoundException(errMsg);
        }

        SearchResult si = (SearchResult) results.next();
        attributes1 = si.getAttributes();
        if (results.hasMore()) {
            si = (SearchResult) results.next();
            String errMsg = "Search is not unique:" + si.getName() + "\n";
            throw new SubjectNotUniqueException(errMsg);
        }
    } catch (NamingException ex) {
        log.error("Ldap NamingException: " + ex.getMessage(), ex);
    }
    return attributes1;
}

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "group.list", required = { "domain" })
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> listGroups(OperationContext opContext) throws NamingException {

    String domain = (String) opContext.getParams().get("domain");

    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

    DomainDn domainDn = nameHelper.newDomainDnFromDomain(domain);

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

    NamingEnumeration<SearchResult> searchResults = userDirContext.search(nameHelper.getGroupsBaseDn(domainDn),
            "(cn=*)", controls);

    List<HashMap<String, Object>> groups = new LinkedList<HashMap<String, Object>>();
    while (searchResults.hasMore()) {
        SearchResult sr = searchResults.next();
        if (nameHelper.isGroupDn(sr.getNameInNamespace().toLowerCase())) {
            HashMap<String, Object> group = new HashMap<String, Object>();
            group.put("groupId", nameHelper.newGroupDn(sr.getNameInNamespace().toLowerCase()).getAsGroupId());
            groups.add(group);//from  ww w .  ja v a 2  s  .  co  m
        }
    }

    HashMap<String, Object> response = new HashMap<String, Object>();
    response.put("groups", groups);

    return response;
}

From source file:org.wso2.carbon.appfactory.s4.integration.DomainMappingManagementService.java

/**
 * Resolve CNAME and A records for the given {@code hostname}.
 *
 * @param domain             hostname to be resolved.
 * @param environmentConfigs environment configuration
 * @return {@link com.google.common.collect.Multimap} of resolved dns entries. This {@link com.google.common.collect.Multimap} will contain the resolved
 * "CNAME" and "A" records from the given {@code hostname}
 * @throws AppFactoryException if error occurred while the operation
 *///from  ww  w  .ja  v  a 2s .  co m
public Multimap<String, String> resolveDNS(String domain, Hashtable<String, String> environmentConfigs)
        throws AppFactoryException, DomainMappingVerificationException {
    // result mutimap of dns records. Contains the cname and records resolved by the given hostname
    // ex:  CNAME   => foo.com,bar.com
    //      A       => 192.1.2.3 , 192.3.4.5
    Multimap<String, String> dnsRecordsResult = ArrayListMultimap.create();
    Attributes dnsRecords;
    boolean isARecordFound = false;
    boolean isCNAMEFound = false;

    try {
        if (log.isDebugEnabled()) {
            log.debug("DNS validation: resolving DNS for " + domain + " " + "(A/CNAME)");
        }
        DirContext context = new InitialDirContext(environmentConfigs);
        String[] dnsRecordsToCheck = new String[] { DNS_A_RECORD, DNS_CNAME_RECORD };
        dnsRecords = context.getAttributes(domain, dnsRecordsToCheck);
    } catch (NamingException e) {
        String msg = "DNS validation: DNS query failed for: " + domain + ". Error occurred while configuring "
                + "directory context.";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);
    }

    try {
        // looking for for A records
        Attribute aRecords = dnsRecords.get(DNS_A_RECORD);
        if (aRecords != null && aRecords.size() > 0) { // if an A record exists
            NamingEnumeration aRecordHosts = aRecords.getAll(); // get all resolved A entries
            String aHost;
            while (aRecordHosts.hasMore()) {
                isARecordFound = true;
                aHost = (String) aRecordHosts.next();
                dnsRecordsResult.put(DNS_A_RECORD, aHost);
                if (log.isDebugEnabled()) {
                    log.debug("DNS validation: A record found: " + aHost);
                }
            }
        }

        // looking for CNAME records
        Attribute cnameRecords = dnsRecords.get(DNS_CNAME_RECORD);
        if (cnameRecords != null && cnameRecords.size() > 0) { // if CNAME record exists
            NamingEnumeration cnameRecordHosts = cnameRecords.getAll(); // get all resolved CNAME entries for hostname
            String cnameHost;
            while (cnameRecordHosts.hasMore()) {
                isCNAMEFound = true;
                cnameHost = (String) cnameRecordHosts.next();
                if (cnameHost.endsWith(".")) {
                    // Since DNS records are end with "." we are removing it.
                    // For example real dns entry for www.google.com is www.google.com.
                    cnameHost = cnameHost.substring(0, cnameHost.lastIndexOf('.'));
                }
                dnsRecordsResult.put(DNS_CNAME_RECORD, cnameHost);
                if (log.isDebugEnabled()) {
                    log.debug("DNS validation: recurring on CNAME record towards host " + cnameHost);
                }
                dnsRecordsResult.putAll(resolveDNS(cnameHost, environmentConfigs)); // recursively resolve cnameHost
            }
        }

        if (!isARecordFound && !isCNAMEFound && log.isDebugEnabled()) {
            log.debug("DNS validation: No CNAME or A record found for domain: '" + domain);
        }
        return dnsRecordsResult;
    } catch (NamingException ne) {
        String msg = "DNS validation: DNS query failed for: " + domain + ". Provided domain: " + domain
                + " might be a " + "non existing domain.";
        // we are logging this as warn messages since this is caused, due to an user error. For example if the
        // user entered a rubbish custom url(Or a url which is, CNAME record is not propagated at the
        // time of adding the url), then url validation will fail but it is not an system error
        log.warn(msg, ne);
        throw new DomainMappingVerificationException(msg, ne);
    }
}