Search in sources :

Example 11 with NamingEnumeration

use of javax.naming.NamingEnumeration in project spring-security by spring-projects.

the class SpringSecurityLdapTemplate method searchForMultipleAttributeValues.

/**
	 * Performs a search using the supplied filter and returns the values of each named
	 * attribute found in all entries matched by the search. Note that one directory entry
	 * may have several values for the attribute. Intended for role searches and similar
	 * scenarios.
	 *
	 * @param base the DN to search in
	 * @param filter search filter to use
	 * @param params the parameters to substitute in the search filter
	 * @param attributeNames the attributes' values that are to be retrieved.
	 *
	 * @return the set of String values for each attribute found in all the matching
	 * entries. The attribute name is the key for each set of values. In addition each map
	 * contains the DN as a String with the key predefined key {@link #DN_KEY}.
	 */
public Set<Map<String, List<String>>> searchForMultipleAttributeValues(final String base, final String filter, final Object[] params, final String[] attributeNames) {
    // Escape the params acording to RFC2254
    Object[] encodedParams = new String[params.length];
    for (int i = 0; i < params.length; i++) {
        encodedParams[i] = LdapEncoder.filterEncode(params[i].toString());
    }
    String formattedFilter = MessageFormat.format(filter, encodedParams);
    logger.debug("Using filter: " + formattedFilter);
    final HashSet<Map<String, List<String>>> set = new HashSet<Map<String, List<String>>>();
    ContextMapper roleMapper = new ContextMapper() {

        public Object mapFromContext(Object ctx) {
            DirContextAdapter adapter = (DirContextAdapter) ctx;
            Map<String, List<String>> record = new HashMap<String, List<String>>();
            if (attributeNames == null || attributeNames.length == 0) {
                try {
                    for (NamingEnumeration ae = adapter.getAttributes().getAll(); ae.hasMore(); ) {
                        Attribute attr = (Attribute) ae.next();
                        extractStringAttributeValues(adapter, record, attr.getID());
                    }
                } catch (NamingException x) {
                    org.springframework.ldap.support.LdapUtils.convertLdapException(x);
                }
            } else {
                for (String attributeName : attributeNames) {
                    extractStringAttributeValues(adapter, record, attributeName);
                }
            }
            record.put(DN_KEY, Arrays.asList(getAdapterDN(adapter)));
            set.add(record);
            return null;
        }
    };
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(searchControls.getSearchScope());
    ctls.setReturningAttributes(attributeNames != null && attributeNames.length > 0 ? attributeNames : null);
    search(base, formattedFilter, ctls, roleMapper);
    return set;
}
Also used : HashMap(java.util.HashMap) Attribute(javax.naming.directory.Attribute) NamingEnumeration(javax.naming.NamingEnumeration) DirContextAdapter(org.springframework.ldap.core.DirContextAdapter) ArrayList(java.util.ArrayList) List(java.util.List) NamingException(javax.naming.NamingException) SearchControls(javax.naming.directory.SearchControls) HashMap(java.util.HashMap) Map(java.util.Map) ContextMapper(org.springframework.ldap.core.ContextMapper) HashSet(java.util.HashSet)

Example 12 with NamingEnumeration

use of javax.naming.NamingEnumeration in project nhin-d by DirectProject.

the class LDAPResearchTest method testLdapSearch.

@SuppressWarnings("unchecked")
public void testLdapSearch() throws Exception {
    CertCacheFactory.getInstance().flushAll();
    int port = configuration.getLdapPort();
    String url = "ldap://localhost:" + port + "/" + "cn=lookupTest";
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    InitialContext initialContext = new InitialContext(env);
    assertNotNull(initialContext);
    DirContext dirContext = (DirContext) initialContext.lookup("");
    Attributes attributes = dirContext.getAttributes("");
    assertNotNull(attributes);
    NamingEnumeration<Attribute> namingEnum = (NamingEnumeration<Attribute>) attributes.getAll();
    while (namingEnum.hasMoreElements()) {
        Attribute attr = namingEnum.nextElement();
        System.out.println("Name: " + attr.getID() + "\r\nValue: " + attr.get() + "\r\n\r\n");
    }
    //Set<SearchResult> results = searchDNs( "(email=gm2552@cerner.com)", "", "ou=privKeys, ou=cerner, ou=com", 
    //        SearchControls.SUBTREE_SCOPE , dirContext);
    LdapStoreConfiguration ldapStoreConfiguration = new LdapStoreConfiguration(new String[] { url }, "", "email", "privKeyStore", "X509");
    LdapCertificateStoreProvider provider = new LdapCertificateStoreProvider(ldapStoreConfiguration, null, null);
    LDAPCertificateStore certificateResolver = (LDAPCertificateStore) provider.get();
    Collection<X509Certificate> certs = certificateResolver.getCertificates("gm2552@cerner.com");
    /*LdapEnvironment ldapEnvironment = new LdapEnvironment(env, "privKeyStore", "", "email");
		LdapCertUtilImpl ldapcertUtilImpl = new LdapCertUtilImpl(ldapEnvironment, "", "X.509");
		LDAPCertificateStore ldapCertStore = new LDAPCertificateStore(ldapcertUtilImpl, new KeyStoreCertificateStore(), null);
		
		Collection<X509Certificate> certs = ldapCertStore.getCertificates("gm2552@cerner.com");
		*/
    assertEquals(1, certs.size());
    X509Certificate cert = certs.iterator().next();
    assertFalse(cert instanceof X509CertificateEx);
    assertTrue(cert.getSubjectX500Principal().toString().contains("bob@nhind.hsgincubator.com"));
}
Also used : LdapStoreConfiguration(org.nhindirect.stagent.cert.impl.LdapStoreConfiguration) BasicAttribute(javax.naming.directory.BasicAttribute) Attribute(javax.naming.directory.Attribute) Hashtable(java.util.Hashtable) BasicAttributes(javax.naming.directory.BasicAttributes) Attributes(javax.naming.directory.Attributes) NamingEnumeration(javax.naming.NamingEnumeration) DirContext(javax.naming.directory.DirContext) InitialContext(javax.naming.InitialContext) X509Certificate(java.security.cert.X509Certificate) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) LDAPCertificateStore(org.nhindirect.stagent.cert.impl.LDAPCertificateStore) LdapCertificateStoreProvider(org.nhindirect.stagent.cert.impl.provider.LdapCertificateStoreProvider)

Example 13 with NamingEnumeration

use of javax.naming.NamingEnumeration in project nhin-d by DirectProject.

the class LDAPResearchTest method testDummy.

@SuppressWarnings("unchecked")
public void testDummy() throws Exception {
    CertCacheFactory.getInstance().flushAll();
    DirContext dirContext = createContext("cn=lookupTest");
    Attributes attributes = dirContext.getAttributes("");
    assertNotNull(attributes);
    NamingEnumeration<Attribute> namingEnum = (NamingEnumeration<Attribute>) attributes.getAll();
    while (namingEnum.hasMoreElements()) {
        Attribute attr = namingEnum.nextElement();
        System.out.println("Name: " + attr.getID() + "\r\nValue: " + attr.get() + "\r\n\r\n");
    }
    Set<SearchResult> results = searchDNs("(email=gm2552@cerner.com)", "", "ou=privKeys, ou=cerner, ou=com", SearchControls.SUBTREE_SCOPE, dirContext);
    for (SearchResult result : results) {
        System.out.println(result.getName());
        // get the priv cert
        String privKey = (String) result.getAttributes().get("privKeyStore").get();
        System.out.println("Privkey BASE64: " + privKey);
    }
}
Also used : 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) DirContext(javax.naming.directory.DirContext)

Example 14 with NamingEnumeration

use of javax.naming.NamingEnumeration in project OpenAM by OpenRock.

the class SMSLdapObject method copyModItemsToModifyRequest.

// Method to covert JNDI ModificationItems to LDAPModificationSet
private static ModifyRequest copyModItemsToModifyRequest(DN dn, ModificationItem[] mods) throws SMSException {
    ModifyRequest modifyRequest = LDAPRequests.newModifyRequest(dn);
    try {
        for (ModificationItem mod : mods) {
            Attribute attribute = mod.getAttribute();
            LinkedAttribute attr = new LinkedAttribute(attribute.getID());
            for (NamingEnumeration ne = attribute.getAll(); ne.hasMore(); ) {
                attr.add(ne.next());
            }
            switch(mod.getModificationOp()) {
                case DirContext.ADD_ATTRIBUTE:
                    modifyRequest.addModification(new Modification(ModificationType.ADD, attr));
                    break;
                case DirContext.REPLACE_ATTRIBUTE:
                    modifyRequest.addModification(new Modification(ModificationType.REPLACE, attr));
                    break;
                case DirContext.REMOVE_ATTRIBUTE:
                    modifyRequest.addModification(new Modification(ModificationType.DELETE, attr));
                    break;
            }
        }
    } catch (NamingException nne) {
        throw new SMSException(nne, "sms-cannot-copy-fromModItemToModSet");
    }
    return modifyRequest;
}
Also used : ModificationItem(javax.naming.directory.ModificationItem) Modification(org.forgerock.opendj.ldap.Modification) Attribute(javax.naming.directory.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) SMSException(com.sun.identity.sm.SMSException) NamingEnumeration(javax.naming.NamingEnumeration) NamingException(javax.naming.NamingException) ModifyRequest(org.forgerock.opendj.ldap.requests.ModifyRequest) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute)

Example 15 with NamingEnumeration

use of javax.naming.NamingEnumeration in project OpenAM by OpenRock.

the class SMSEmbeddedLdapObject method copyModItemsToLDAPModList.

// Method to covert JNDI ModificationItems to LDAPModificationSet
private static List copyModItemsToLDAPModList(ModificationItem[] mods) throws SMSException {
    if ((mods == null) || (mods.length == 0)) {
        return null;
    }
    List<LDAPModification> modList = new ArrayList<>(mods.length);
    try {
        for (ModificationItem mod : mods) {
            Attribute dAttr = mod.getAttribute();
            String attrName = dAttr.getID();
            List<String> values = new ArrayList<>();
            for (NamingEnumeration ne = dAttr.getAll(); ne.hasMore(); ) {
                values.add((String) ne.next());
            }
            ModificationType modType = null;
            switch(mod.getModificationOp()) {
                case DirContext.ADD_ATTRIBUTE:
                    modType = ModificationType.ADD;
                    break;
                case DirContext.REPLACE_ATTRIBUTE:
                    modType = ModificationType.REPLACE;
                    break;
                case DirContext.REMOVE_ATTRIBUTE:
                    modType = ModificationType.DELETE;
                    break;
            }
            if (modType != null) {
                modList.add(new LDAPModification(modType, new LDAPAttribute(attrName, values)));
            }
        }
    } catch (NamingException nne) {
        throw (new SMSException(nne, "sms-cannot-copy-fromModItemToModSet"));
    }
    return (modList);
}
Also used : ModificationItem(javax.naming.directory.ModificationItem) LDAPAttribute(org.opends.server.protocols.ldap.LDAPAttribute) Attribute(javax.naming.directory.Attribute) LDAPAttribute(org.opends.server.protocols.ldap.LDAPAttribute) ModificationType(org.forgerock.opendj.ldap.ModificationType) SMSException(com.sun.identity.sm.SMSException) LDAPModification(org.opends.server.protocols.ldap.LDAPModification) ArrayList(java.util.ArrayList) NamingEnumeration(javax.naming.NamingEnumeration) NamingException(javax.naming.NamingException)

Aggregations

NamingEnumeration (javax.naming.NamingEnumeration)48 Attribute (javax.naming.directory.Attribute)22 SearchResult (javax.naming.directory.SearchResult)20 NamingException (javax.naming.NamingException)19 Attributes (javax.naming.directory.Attributes)19 SearchControls (javax.naming.directory.SearchControls)18 DirContext (javax.naming.directory.DirContext)14 ArrayList (java.util.ArrayList)11 LdapContext (javax.naming.ldap.LdapContext)10 Test (org.junit.Test)9 InitialContext (javax.naming.InitialContext)7 Hashtable (java.util.Hashtable)6 Context (javax.naming.Context)6 InitialDirContext (javax.naming.directory.InitialDirContext)6 HashMap (java.util.HashMap)5 IOException (java.io.IOException)3 HashSet (java.util.HashSet)3 Binding (javax.naming.Binding)3 NameClassPair (javax.naming.NameClassPair)3 NameNotFoundException (javax.naming.NameNotFoundException)3