Search in sources :

Example 21 with NameParser

use of javax.naming.NameParser in project activemq-artemis by apache.

the class LDAPLoginModule method resolveDN.

private String resolveDN(String username, List<String> roles) throws FailedLoginException {
    String dn = null;
    MessageFormat userSearchMatchingFormat;
    boolean userSearchSubtreeBool;
    if (logger.isDebugEnabled()) {
        logger.debug("Create the LDAP initial context.");
    }
    try {
        openContext();
    } catch (Exception ne) {
        FailedLoginException ex = new FailedLoginException("Error opening LDAP connection");
        ex.initCause(ne);
        throw ex;
    }
    if (!isLoginPropertySet(USER_SEARCH_MATCHING))
        return dn;
    userSearchMatchingFormat = new MessageFormat(getLDAPPropertyValue(USER_SEARCH_MATCHING));
    userSearchSubtreeBool = Boolean.valueOf(getLDAPPropertyValue(USER_SEARCH_SUBTREE)).booleanValue();
    try {
        String filter = userSearchMatchingFormat.format(new String[] { doRFC2254Encoding(username) });
        SearchControls constraints = new SearchControls();
        if (userSearchSubtreeBool) {
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }
        // setup attributes
        List<String> list = new ArrayList<>();
        if (isLoginPropertySet(USER_ROLE_NAME)) {
            list.add(getLDAPPropertyValue(USER_ROLE_NAME));
        }
        String[] attribs = new String[list.size()];
        list.toArray(attribs);
        constraints.setReturningAttributes(attribs);
        if (logger.isDebugEnabled()) {
            logger.debug("Get the user DN.");
            logger.debug("Looking for the user in LDAP with ");
            logger.debug("  base DN: " + getLDAPPropertyValue(USER_BASE));
            logger.debug("  filter: " + filter);
        }
        NamingEnumeration<SearchResult> results = null;
        try {
            results = Subject.doAs(brokerGssapiIdentity, (PrivilegedExceptionAction<NamingEnumeration<SearchResult>>) () -> context.search(getLDAPPropertyValue(USER_BASE), filter, constraints));
        } catch (PrivilegedActionException e) {
            Exception cause = e.getException();
            FailedLoginException ex = new FailedLoginException("Error executing search query to resolve DN");
            ex.initCause(cause);
            throw ex;
        }
        if (results == null || !results.hasMore()) {
            throw new FailedLoginException("User " + username + " not found in LDAP.");
        }
        SearchResult result = results.next();
        if (results.hasMore()) {
        // ignore for now
        }
        if (result.isRelative()) {
            logger.debug("LDAP returned a relative name: " + result.getName());
            NameParser parser = context.getNameParser("");
            Name contextName = parser.parse(context.getNameInNamespace());
            Name baseName = parser.parse(getLDAPPropertyValue(USER_BASE));
            Name entryName = parser.parse(result.getName());
            Name name = contextName.addAll(baseName);
            name = name.addAll(entryName);
            dn = name.toString();
        } else {
            logger.debug("LDAP returned an absolute name: " + result.getName());
            try {
                URI uri = new URI(result.getName());
                String path = uri.getPath();
                if (path.startsWith("/")) {
                    dn = path.substring(1);
                } else {
                    dn = path;
                }
            } catch (URISyntaxException e) {
                closeContext();
                FailedLoginException ex = new FailedLoginException("Error parsing absolute name as URI.");
                ex.initCause(e);
                throw ex;
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Using DN [" + dn + "] for binding.");
        }
        Attributes attrs = result.getAttributes();
        if (attrs == null) {
            throw new FailedLoginException("User found, but LDAP entry malformed: " + username);
        }
        if (isLoginPropertySet(USER_ROLE_NAME)) {
            Attribute roleNames = attrs.get(getLDAPPropertyValue(USER_ROLE_NAME));
            if (roleNames != null) {
                NamingEnumeration<?> e = roleNames.getAll();
                while (e.hasMore()) {
                    String roleDnString = (String) e.next();
                    if (isRoleAttributeSet) {
                        // parse out the attribute from the group Dn
                        LdapName ldapRoleName = new LdapName(roleDnString);
                        for (int i = 0; i < ldapRoleName.size(); i++) {
                            Rdn candidate = ldapRoleName.getRdn(i);
                            if (roleAttributeName.equals(candidate.getType())) {
                                roles.add((String) candidate.getValue());
                            }
                        }
                    } else {
                        roles.add(roleDnString);
                    }
                }
            }
        }
    } catch (CommunicationException e) {
        closeContext();
        FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
        ex.initCause(e);
        throw ex;
    } catch (NamingException e) {
        closeContext();
        FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
        ex.initCause(e);
        throw ex;
    }
    return dn;
}
Also used : Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) LdapName(javax.naming.ldap.LdapName) Name(javax.naming.Name) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException) Rdn(javax.naming.ldap.Rdn) MessageFormat(java.text.MessageFormat) CommunicationException(javax.naming.CommunicationException) PrivilegedActionException(java.security.PrivilegedActionException) SearchResult(javax.naming.directory.SearchResult) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) LoginException(javax.security.auth.login.LoginException) URISyntaxException(java.net.URISyntaxException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException) FailedLoginException(javax.security.auth.login.FailedLoginException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) CommunicationException(javax.naming.CommunicationException) LdapName(javax.naming.ldap.LdapName) FailedLoginException(javax.security.auth.login.FailedLoginException) NameParser(javax.naming.NameParser)

Example 22 with NameParser

use of javax.naming.NameParser in project geronimo-xbean by apache.

the class UnmodifiableContextTest method testRemoveBinding.

public void testRemoveBinding() throws Exception {
    Map map = new HashMap();
    map.put("string", STRING_VAL);
    map.put("nested/context/string", STRING_VAL);
    map.put("a/b/c/d/e/string", STRING_VAL);
    map.put("a/b/c/d/e/one", new Integer(1));
    map.put("a/b/c/d/e/two", new Integer(2));
    map.put("a/b/c/d/e/three", new Integer(3));
    MutableContext context = new MutableContext(map);
    assertEq(map, context);
    assertUnmodifiable(context);
    // remove from an exisitng node
    map.remove("a/b/c/d/e/three");
    NameParser parser = context.getNameParser();
    context.removeDeepBinding(parser.parse("a/b/c/d/e/three"), true);
    assertEq(map, context);
    assertUnmodifiable(context);
    // remove a deep single element element... empty nodes should be removed
    map.remove("nested/context/string");
    context.removeDeepBinding(parser.parse("nested/context/string"), true);
    assertEq(map, context);
    assertUnmodifiable(context);
}
Also used : HashMap(java.util.HashMap) Map(java.util.Map) HashMap(java.util.HashMap) NameParser(javax.naming.NameParser)

Example 23 with NameParser

use of javax.naming.NameParser in project geronimo-xbean by apache.

the class UnmodifiableContextTest method testAddBinding.

public void testAddBinding() throws Exception {
    Map map = new HashMap();
    map.put("string", STRING_VAL);
    map.put("nested/context/string", STRING_VAL);
    map.put("a/b/c/d/e/string", STRING_VAL);
    map.put("a/b/c/d/e/one", new Integer(1));
    map.put("a/b/c/d/e/two", new Integer(2));
    map.put("a/b/c/d/e/three", new Integer(3));
    MutableContext context = new MutableContext(map);
    assertEq(map, context);
    assertUnmodifiable(context);
    // add a new deep tree
    map.put("uno/dos/tres", new Integer(123));
    NameParser parser = context.getNameParser();
    context.addDeepBinding(parser.parse("uno/dos/tres"), new Integer(123), false, true);
    assertEq(map, context);
    assertUnmodifiable(context);
    // modify an existing context
    map.put("a/b/c/d/e/four", new Integer(4));
    context.addDeepBinding(parser.parse("a/b/c/d/e/four"), new Integer(4), false, true);
    assertEq(map, context);
    assertUnmodifiable(context);
}
Also used : HashMap(java.util.HashMap) Map(java.util.Map) HashMap(java.util.HashMap) NameParser(javax.naming.NameParser)

Example 24 with NameParser

use of javax.naming.NameParser in project deltaspike by apache.

the class JndiUtils method list.

/**
 * Resolves an instances for the given naming context.
 *
 * @param name       context name
 * @param type       target type
 * @param <T>        type
 * @return the found instances, null otherwise
 */
public static <T> Map<String, T> list(String name, Class<T> type) {
    Map<String, T> result = new HashMap<String, T>();
    try {
        NameParser nameParser = initialContext.getNameParser(name);
        NamingEnumeration<NameClassPair> enumeration = initialContext.list(name);
        while (enumeration.hasMoreElements()) {
            try {
                NameClassPair binding = enumeration.nextElement();
                Name bindingName = nameParser.parse(name).add(binding.getName());
                result.put(binding.getName(), lookup(bindingName, type));
            } catch (NamingException e) {
                if (LOG.isLoggable(Level.FINEST)) {
                    // this is expected if there is no entry in JNDI for the requested name or type
                    // so finest level is ok, if devs want to see it they can enable this logger level.
                    LOG.log(Level.FINEST, "InitialContext#list failed!", e);
                }
            }
        }
    } catch (NamingException e) {
        // this is fine at this point, since the individual lines will be caught currently.
        LOG.log(Level.WARNING, "Problem reading the name of the JNDI location " + name + " or failuring listing pairs.", e);
    }
    return result;
}
Also used : HashMap(java.util.HashMap) NameClassPair(javax.naming.NameClassPair) NamingException(javax.naming.NamingException) NameParser(javax.naming.NameParser) Name(javax.naming.Name)

Aggregations

NameParser (javax.naming.NameParser)24 Name (javax.naming.Name)21 InitialContext (javax.naming.InitialContext)9 NamingException (javax.naming.NamingException)8 HashMap (java.util.HashMap)7 Context (javax.naming.Context)7 CompositeName (javax.naming.CompositeName)6 CoreException (com.cosylab.acs.maci.CoreException)4 ArrayList (java.util.ArrayList)4 Attributes (javax.naming.directory.Attributes)4 SearchControls (javax.naming.directory.SearchControls)4 SearchResult (javax.naming.directory.SearchResult)4 URI (java.net.URI)3 URISyntaxException (java.net.URISyntaxException)3 Entry (java.util.Map.Entry)3 NameNotFoundException (javax.naming.NameNotFoundException)3 PartialResultException (javax.naming.PartialResultException)3 Test (org.junit.Test)3 Map (java.util.Map)2 InvalidNameException (javax.naming.InvalidNameException)2