Search in sources :

Example 71 with DirContext

use of javax.naming.directory.DirContext in project Openfire by igniterealtime.

the class LdapVCardProvider method getLdapAttributes.

/**
     * Creates a mapping of requested LDAP attributes to their values for the given user.
     *
     * @param username User we are looking up in LDAP.
     * @return Map of LDAP attribute to setting.
     */
private Map<String, String> getLdapAttributes(String username) {
    // Un-escape username
    username = JID.unescapeNode(username);
    Map<String, String> map = new HashMap<>();
    DirContext ctx = null;
    try {
        String userDN = manager.findUserDN(username);
        ctx = manager.getContext(manager.getUsersBaseDN(username));
        Attributes attrs = ctx.getAttributes(userDN, template.getAttributes());
        for (String attribute : template.getAttributes()) {
            javax.naming.directory.Attribute attr = attrs.get(attribute);
            String value;
            if (attr == null) {
                Log.debug("LdapVCardProvider: No ldap value found for attribute '" + attribute + "'");
                value = "";
            } else {
                Object ob = attrs.get(attribute).get();
                Log.debug("LdapVCardProvider: Found attribute " + attribute + " of type: " + ob.getClass());
                if (ob instanceof String) {
                    value = (String) ob;
                } else {
                    value = Base64.encodeBytes((byte[]) ob);
                }
            }
            Log.debug("LdapVCardProvider: Ldap attribute '" + attribute + "'=>'" + value + "'");
            map.put(attribute, value);
        }
        return map;
    } catch (Exception e) {
        Log.error(e.getMessage(), e);
        return Collections.emptyMap();
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (Exception e) {
        // Ignore.
        }
    }
}
Also used : HashMap(java.util.HashMap) Attributes(javax.naming.directory.Attributes) DirContext(javax.naming.directory.DirContext) NotFoundException(org.jivesoftware.util.NotFoundException) AlreadyExistsException(org.jivesoftware.util.AlreadyExistsException)

Example 72 with DirContext

use of javax.naming.directory.DirContext in project orientdb by orientechnologies.

the class OStorageRemote method parseServerURLs.

/**
   * Parse the URLs. Multiple URLs must be separated by semicolon (;)
   */
protected void parseServerURLs() {
    String lastHost = null;
    int dbPos = url.indexOf('/');
    if (dbPos == -1) {
        // SHORT FORM
        addHost(url);
        lastHost = url;
        name = url;
    } else {
        name = url.substring(url.lastIndexOf("/") + 1);
        for (String host : url.substring(0, dbPos).split(ADDRESS_SEPARATOR)) {
            lastHost = host;
            addHost(host);
        }
    }
    synchronized (serverURLs) {
        if (serverURLs.size() == 1 && OGlobalConfiguration.NETWORK_BINARY_DNS_LOADBALANCING_ENABLED.getValueAsBoolean()) {
            // LOOK FOR LOAD BALANCING DNS TXT RECORD
            final String primaryServer = lastHost;
            OLogManager.instance().debug(this, "Retrieving URLs from DNS '%s' (timeout=%d)...", primaryServer, OGlobalConfiguration.NETWORK_BINARY_DNS_LOADBALANCING_TIMEOUT.getValueAsInteger());
            try {
                final Hashtable<String, String> env = new Hashtable<String, String>();
                env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
                env.put("com.sun.jndi.ldap.connect.timeout", OGlobalConfiguration.NETWORK_BINARY_DNS_LOADBALANCING_TIMEOUT.getValueAsString());
                final DirContext ictx = new InitialDirContext(env);
                final String hostName = !primaryServer.contains(":") ? primaryServer : primaryServer.substring(0, primaryServer.indexOf(":"));
                final Attributes attrs = ictx.getAttributes(hostName, new String[] { "TXT" });
                final Attribute attr = attrs.get("TXT");
                if (attr != null) {
                    for (int i = 0; i < attr.size(); ++i) {
                        String configuration = (String) attr.get(i);
                        if (configuration.startsWith("\""))
                            configuration = configuration.substring(1, configuration.length() - 1);
                        if (configuration != null) {
                            serverURLs.clear();
                            final String[] parts = configuration.split(" ");
                            for (String part : parts) {
                                if (part.startsWith("s=")) {
                                    addHost(part.substring("s=".length()));
                                }
                            }
                        }
                    }
                }
            } catch (NamingException ignore) {
            }
        }
    }
}
Also used : Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 73 with DirContext

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

the class ActiveDirectoryLdapAuthenticationProvider method doAuthentication.

@Override
protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationToken auth) {
    String username = auth.getName();
    String password = (String) auth.getCredentials();
    DirContext ctx = bindAsUser(username, password);
    try {
        return searchForUser(ctx, username);
    } catch (NamingException e) {
        logger.error("Failed to locate directory entry for authenticated user: " + username, e);
        throw badCredentials(e);
    } finally {
        LdapUtils.closeContext(ctx);
    }
}
Also used : NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext)

Example 74 with DirContext

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

the class SpringSecurityLdapTemplateITests method namingExceptionIsTranslatedCorrectly.

// @Test
// public void testNameExistsForInValidNameFails() {
// assertThat(template.nameExists("ou=doesntexist,dc=springframework,dc=org")).isFalse();
// }
//
// @Test
// public void testNameExistsForValidNameSucceeds() {
// assertThat(template.nameExists("ou=groups,dc=springframework,dc=org")).isTrue();
// }
@Test
public void namingExceptionIsTranslatedCorrectly() {
    try {
        template.executeReadOnly(new ContextExecutor() {

            public Object executeWithContext(DirContext dirContext) throws NamingException {
                throw new NamingException();
            }
        });
        fail("Expected UncategorizedLdapException on NamingException");
    } catch (UncategorizedLdapException expected) {
    }
}
Also used : NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) UncategorizedLdapException(org.springframework.ldap.UncategorizedLdapException) ContextExecutor(org.springframework.ldap.core.ContextExecutor)

Example 75 with DirContext

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

the class LdapUserDetailsManager method getUserAuthorities.

/**
	 *
	 * @param dn the distinguished name of the entry - may be either relative to the base
	 * context or a complete DN including the name of the context (either is supported).
	 * @param username the user whose roles are required.
	 * @return the granted authorities returned by the group search
	 */
@SuppressWarnings("unchecked")
List<GrantedAuthority> getUserAuthorities(final DistinguishedName dn, final String username) {
    SearchExecutor se = new SearchExecutor() {

        public NamingEnumeration<SearchResult> executeSearch(DirContext ctx) throws NamingException {
            DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx);
            SearchControls ctrls = new SearchControls();
            ctrls.setReturningAttributes(new String[] { groupRoleAttributeName });
            return ctx.search(groupSearchBase, groupSearchFilter, new String[] { fullDn.toUrl(), username }, ctrls);
        }
    };
    AttributesMapperCallbackHandler roleCollector = new AttributesMapperCallbackHandler(roleMapper);
    template.search(se, roleCollector);
    return roleCollector.getList();
}
Also used : DistinguishedName(org.springframework.ldap.core.DistinguishedName) SearchResult(javax.naming.directory.SearchResult) SearchControls(javax.naming.directory.SearchControls) DirContext(javax.naming.directory.DirContext) SearchExecutor(org.springframework.ldap.core.SearchExecutor) AttributesMapperCallbackHandler(org.springframework.ldap.core.AttributesMapperCallbackHandler)

Aggregations

DirContext (javax.naming.directory.DirContext)111 NamingException (javax.naming.NamingException)51 InitialDirContext (javax.naming.directory.InitialDirContext)43 SearchResult (javax.naming.directory.SearchResult)27 SearchControls (javax.naming.directory.SearchControls)24 Attributes (javax.naming.directory.Attributes)21 Attribute (javax.naming.directory.Attribute)17 IOException (java.io.IOException)16 NamingEnumeration (javax.naming.NamingEnumeration)16 Hashtable (java.util.Hashtable)14 Test (org.junit.Test)14 DistinguishedName (org.springframework.ldap.core.DistinguishedName)11 ProxyDirContext (org.apache.naming.resources.ProxyDirContext)10 WebDirContext (org.apache.naming.resources.WebDirContext)9 ArrayList (java.util.ArrayList)8 BaseDirContext (org.apache.naming.resources.BaseDirContext)8 FileDirContext (org.apache.naming.resources.FileDirContext)8 WARDirContext (org.apache.naming.resources.WARDirContext)8 Name (javax.naming.Name)7 BasicAttribute (javax.naming.directory.BasicAttribute)7