Search in sources :

Example 21 with NamingEnumeration

use of javax.naming.NamingEnumeration in project karaf by apache.

the class LDAPCache method doGetUserRoles.

private String[] doGetUserRoles(String user, String userDn, String userDnNamespace) throws NamingException {
    DirContext context = open();
    SearchControls controls = new SearchControls();
    if (options.getRoleSearchSubtree()) {
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    } else {
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    }
    String filter = options.getRoleFilter();
    if (filter != null) {
        filter = filter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
        filter = filter.replaceAll(Pattern.quote("%dn"), Matcher.quoteReplacement(userDn));
        filter = filter.replaceAll(Pattern.quote("%fqdn"), Matcher.quoteReplacement(userDnNamespace));
        filter = filter.replace("\\", "\\\\");
        LOGGER.debug("Looking for the user roles in LDAP with ");
        LOGGER.debug("  base DN: " + options.getRoleBaseDn());
        LOGGER.debug("  filter: " + filter);
        NamingEnumeration namingEnumeration = context.search(options.getRoleBaseDn(), filter, controls);
        try {
            List<String> rolesList = new ArrayList<>();
            while (namingEnumeration.hasMore()) {
                SearchResult result = (SearchResult) namingEnumeration.next();
                Attributes attributes = result.getAttributes();
                Attribute roles1 = attributes.get(options.getRoleNameAttribute());
                if (roles1 != null) {
                    for (int i = 0; i < roles1.size(); i++) {
                        String role = (String) roles1.get(i);
                        if (role != null) {
                            LOGGER.debug("User {} is a member of role {}", user, role);
                            // handle role mapping
                            Set<String> roleMappings = tryMappingRole(role);
                            if (roleMappings.isEmpty()) {
                                rolesList.add(role);
                            } else {
                                for (String roleMapped : roleMappings) {
                                    rolesList.add(roleMapped);
                                }
                            }
                        }
                    }
                }
            }
            return rolesList.toArray(new String[rolesList.size()]);
        } finally {
            if (namingEnumeration != null) {
                try {
                    namingEnumeration.close();
                } catch (NamingException e) {
                // Ignore
                }
            }
        }
    } else {
        LOGGER.debug("The user role filter is null so no roles are retrieved");
        return new String[] {};
    }
}
Also used : Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext) EventDirContext(javax.naming.event.EventDirContext) DirContext(javax.naming.directory.DirContext)

Example 22 with NamingEnumeration

use of javax.naming.NamingEnumeration in project wildfly by wildfly.

the class ServiceBasedNamingStoreTestCase method testStoredContext.

@Test
public void testStoredContext() throws Exception {
    final ServiceName bindingName = ServiceName.JBOSS.append("foo-stored").append("again");
    bindObject(bindingName, new Context() {

        @Override
        public Object lookup(Name name) throws NamingException {
            if ("blah/blah2".equals(name.toString())) {
                return new Integer(5);
            }
            return null;
        }

        @Override
        public Object lookup(String name) throws NamingException {
            return lookup(new CompositeName(name));
        }

        @Override
        public void bind(Name name, Object obj) throws NamingException {
        }

        @Override
        public void bind(String name, Object obj) throws NamingException {
        }

        @Override
        public void rebind(Name name, Object obj) throws NamingException {
        }

        @Override
        public void rebind(String name, Object obj) throws NamingException {
        }

        @Override
        public void unbind(Name name) throws NamingException {
        }

        @Override
        public void unbind(String name) throws NamingException {
        }

        @Override
        public void rename(Name oldName, Name newName) throws NamingException {
        }

        @Override
        public void rename(String oldName, String newName) throws NamingException {
        }

        @Override
        public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
            return null;
        }

        @Override
        public NamingEnumeration<NameClassPair> list(String name) throws NamingException {
            return null;
        }

        @Override
        public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
            if (!"hi/there".equals(name.toString()))
                throw new IllegalArgumentException("Expected hi/there");
            return null;
        }

        @Override
        public NamingEnumeration<Binding> listBindings(String name) throws NamingException {
            return null;
        }

        @Override
        public void destroySubcontext(Name name) throws NamingException {
        }

        @Override
        public void destroySubcontext(String name) throws NamingException {
        }

        @Override
        public Context createSubcontext(Name name) throws NamingException {
            return null;
        }

        @Override
        public Context createSubcontext(String name) throws NamingException {
            return null;
        }

        @Override
        public Object lookupLink(Name name) throws NamingException {
            return null;
        }

        @Override
        public Object lookupLink(String name) throws NamingException {
            return null;
        }

        @Override
        public NameParser getNameParser(Name name) throws NamingException {
            return null;
        }

        @Override
        public NameParser getNameParser(String name) throws NamingException {
            return null;
        }

        @Override
        public Name composeName(Name name, Name prefix) throws NamingException {
            return null;
        }

        @Override
        public String composeName(String name, String prefix) throws NamingException {
            return null;
        }

        @Override
        public Object addToEnvironment(String propName, Object propVal) throws NamingException {
            return null;
        }

        @Override
        public Object removeFromEnvironment(String propName) throws NamingException {
            return null;
        }

        @Override
        public Hashtable<?, ?> getEnvironment() throws NamingException {
            return null;
        }

        @Override
        public void close() throws NamingException {
        }

        @Override
        public String getNameInNamespace() throws NamingException {
            return null;
        }
    });
    final NamingContext ctx = new NamingContext(new CompositeName(), store, null);
    final Object obj = ctx.lookup(new CompositeName("foo-stored/again/blah/blah2"));
    ctx.listBindings("foo-stored/again/hi/there");
    assertNotNull(obj);
    assertEquals(new Integer(5), obj);
}
Also used : StopContext(org.jboss.msc.service.StopContext) Context(javax.naming.Context) StartContext(org.jboss.msc.service.StartContext) Hashtable(java.util.Hashtable) CompositeName(javax.naming.CompositeName) NamingEnumeration(javax.naming.NamingEnumeration) CompositeName(javax.naming.CompositeName) Name(javax.naming.Name) ServiceName(org.jboss.msc.service.ServiceName) ServiceName(org.jboss.msc.service.ServiceName) NamingException(javax.naming.NamingException) NameParser(javax.naming.NameParser) Test(org.junit.Test)

Example 23 with NamingEnumeration

use of javax.naming.NamingEnumeration in project uPortal by Jasig.

the class SimpleLdapSecurityContext method authenticate.

/** Authenticates the user. */
public synchronized void authenticate() throws PortalSecurityException {
    this.isauth = false;
    ILdapServer ldapConn;
    String propFile = ctxProperties.getProperty(LDAP_PROPERTIES_CONNECTION_NAME);
    if (propFile != null && propFile.length() > 0)
        ldapConn = LdapServices.getLdapServer(propFile);
    else
        ldapConn = LdapServices.getDefaultLdapServer();
    String creds = new String(this.myOpaqueCredentials.credentialstring);
    if (this.myPrincipal.UID != null && !this.myPrincipal.UID.trim().equals("") && this.myOpaqueCredentials.credentialstring != null && !creds.trim().equals("")) {
        DirContext conn = null;
        NamingEnumeration results = null;
        StringBuffer user = new StringBuffer("(");
        String first_name = null;
        String last_name = null;
        user.append(ldapConn.getUidAttribute()).append("=");
        user.append(this.myPrincipal.UID).append(")");
        log.debug("SimpleLdapSecurityContext: Looking for {}", user.toString());
        try {
            conn = ldapConn.getConnection();
            // set up search controls
            SearchControls searchCtls = new SearchControls();
            searchCtls.setReturningAttributes(attributes);
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            // do lookup
            if (conn != null) {
                try {
                    results = conn.search(ldapConn.getBaseDN(), user.toString(), searchCtls);
                    if (results != null) {
                        if (!results.hasMore()) {
                            log.error("SimpleLdapSecurityContext: user not found: {}", this.myPrincipal.UID);
                        }
                        while (results != null && results.hasMore()) {
                            SearchResult entry = (SearchResult) results.next();
                            StringBuffer dnBuffer = new StringBuffer();
                            dnBuffer.append(entry.getName()).append(", ");
                            dnBuffer.append(ldapConn.getBaseDN());
                            Attributes attrs = entry.getAttributes();
                            first_name = getAttributeValue(attrs, ATTR_FIRSTNAME);
                            last_name = getAttributeValue(attrs, ATTR_LASTNAME);
                            // re-bind as user
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_PRINCIPAL);
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_CREDENTIALS);
                            conn.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, dnBuffer.toString());
                            conn.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, this.myOpaqueCredentials.credentialstring);
                            searchCtls = new SearchControls();
                            searchCtls.setReturningAttributes(new String[0]);
                            searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);
                            String attrSearch = "(" + ldapConn.getUidAttribute() + "=*)";
                            log.debug("SimpleLdapSecurityContext: Looking in {} for {}", dnBuffer.toString(), attrSearch);
                            conn.search(dnBuffer.toString(), attrSearch, searchCtls);
                            this.isauth = true;
                            this.myPrincipal.FullName = first_name + " " + last_name;
                            log.debug("SimpleLdapSecurityContext: User {} ({}) is authenticated", this.myPrincipal.UID, this.myPrincipal.FullName);
                            // Since LDAP is case-insensitive with respect to uid, force
                            // user name to lower case for use by the portal
                            this.myPrincipal.UID = this.myPrincipal.UID.toLowerCase();
                        }
                    // while (results != null && results.hasMore())
                    } else {
                        log.error("SimpleLdapSecurityContext: No such user: {}", this.myPrincipal.UID);
                    }
                } catch (AuthenticationException ae) {
                    log.info("SimpleLdapSecurityContext: Password invalid for user: " + this.myPrincipal.UID);
                } catch (Exception e) {
                    log.error("SimpleLdapSecurityContext: LDAP Error with user: " + this.myPrincipal.UID + "; ", e);
                    throw new PortalSecurityException("SimpleLdapSecurityContext: LDAP Error" + e + " with user: " + this.myPrincipal.UID);
                } finally {
                    ldapConn.releaseConnection(conn);
                }
            } else {
                log.error("LDAP Server Connection unavailable");
            }
        } catch (final NamingException ne) {
            log.error("Error getting connection to LDAP server.", ne);
        }
    } else {
        // If the principal and/or credential are missing, the context authentication
        // simply fails. It should not be construed that this is an error. It happens for guest access.
        log.info("Principal or OpaqueCredentials not initialized prior to authenticate");
    }
    // Ok...we are now ready to authenticate all of our subcontexts.
    super.authenticate();
    return;
}
Also used : ILdapServer(org.apereo.portal.ldap.ILdapServer) AuthenticationException(javax.naming.AuthenticationException) Attributes(javax.naming.directory.Attributes) NamingEnumeration(javax.naming.NamingEnumeration) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) PortalSecurityException(org.apereo.portal.security.PortalSecurityException) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException) PortalSecurityException(org.apereo.portal.security.PortalSecurityException)

Example 24 with NamingEnumeration

use of javax.naming.NamingEnumeration in project simba-os by cegeka.

the class ActiveDirectoryLoginModule method addADGroupsToUser.

protected void addADGroupsToUser(LdapContext ldapContext, User user, String userCN) throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setReturningAttributes(new String[] { "dn" });
    searchControls.setSearchScope(searchScope);
    GroupRepository groupRepository = GlobalContext.locate(GroupRepository.class);
    String filterGroups = "(&(member=" + userCN + "," + searchBase + ")(objectcategory=group))";
    NamingEnumeration results = ldapContext.search(searchBase, filterGroups, searchControls);
    while (hasMoreResults(results)) {
        String groupCN = ((SearchResult) results.next()).getName();
        Group group = groupRepository.findByCN(groupCN);
        if (group != null) {
            user.addGroup(group);
        }
    }
}
Also used : Group(org.simbasecurity.core.domain.Group) SearchControls(javax.naming.directory.SearchControls) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult) GroupRepository(org.simbasecurity.core.domain.repository.GroupRepository)

Example 25 with NamingEnumeration

use of javax.naming.NamingEnumeration in project zeppelin by apache.

the class ActiveDirectoryGroupRealm method getRoleNamesForUser.

private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set<String> roleNames = new LinkedHashSet<>();
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String userPrincipalName = username;
    if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) {
        userPrincipalName += principalSuffix;
    }
    String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";
    Object[] searchArguments = new Object[] { userPrincipalName };
    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);
    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();
        if (log.isDebugEnabled()) {
            log.debug("Retrieving group names for user [" + sr.getName() + "]");
        }
        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMore()) {
                Attribute attr = (Attribute) ae.next();
                if (attr.getID().equals("memberOf")) {
                    Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);
                    if (log.isDebugEnabled()) {
                        log.debug("Groups found for user [" + username + "]: " + groupNames);
                    }
                    Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
                    roleNames.addAll(rolesForGroups);
                }
            }
        }
    }
    return roleNames;
}
Also used : Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult)

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