Search in sources :

Example 1 with Attributes

use of javax.naming.directory.Attributes in project jetty.project by eclipse.

the class LdapLoginModule method getUserInfo.

/**
     * get the available information about the user
     * <p>
     * for this LoginModule, the credential can be null which will result in a
     * binding ldap authentication scenario
     * <p>
     * roles are also an optional concept if required
     *
     * @param username the user name
     * @return the userinfo for the username
     * @throws Exception if unable to get the user info
     */
public UserInfo getUserInfo(String username) throws Exception {
    Attributes attributes = getUserAttributes(username);
    String pwdCredential = getUserCredentials(attributes);
    if (pwdCredential == null) {
        return null;
    }
    pwdCredential = convertCredentialLdapToJetty(pwdCredential);
    Credential credential = Credential.getCredential(pwdCredential);
    return new LDAPUserInfo(username, credential, attributes);
}
Also used : Credential(org.eclipse.jetty.util.security.Credential) Attributes(javax.naming.directory.Attributes)

Example 2 with Attributes

use of javax.naming.directory.Attributes in project jetty.project by eclipse.

the class LdapLoginModule method getUserRolesByDn.

private List<String> getUserRolesByDn(DirContext dirContext, String userDn) throws LoginException, NamingException {
    List<String> roleList = new ArrayList<String>();
    if (dirContext == null || _roleBaseDn == null || _roleMemberAttribute == null || _roleObjectClass == null) {
        return roleList;
    }
    SearchControls ctls = new SearchControls();
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(new String[] { _roleNameAttribute });
    String filter = "(&(objectClass={0})({1}={2}))";
    Object[] filterArguments = { _roleObjectClass, _roleMemberAttribute, userDn };
    NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    LOG.debug("Found user roles?: " + results.hasMoreElements());
    while (results.hasMoreElements()) {
        SearchResult result = (SearchResult) results.nextElement();
        Attributes attributes = result.getAttributes();
        if (attributes == null) {
            continue;
        }
        Attribute roleAttribute = attributes.get(_roleNameAttribute);
        if (roleAttribute == null) {
            continue;
        }
        NamingEnumeration<?> roles = roleAttribute.getAll();
        while (roles.hasMore()) {
            roleList.add(roles.next().toString());
        }
    }
    return roleList;
}
Also used : Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult)

Example 3 with Attributes

use of javax.naming.directory.Attributes in project tomcat by apache.

the class JNDIRealm method getRoles.

/**
     * Return a List of roles associated with the given User.  Any
     * roles present in the user's directory entry are supplemented by
     * a directory search. If no roles are associated with this user,
     * a zero-length List is returned.
     *
     * @param context The directory context we are searching
     * @param user The User to be checked
     * @return the list of role names
     * @exception NamingException if a directory server error occurs
     */
protected List<String> getRoles(DirContext context, User user) throws NamingException {
    if (user == null)
        return null;
    String dn = user.getDN();
    String username = user.getUserName();
    String userRoleId = user.getUserRoleId();
    if (dn == null || username == null)
        return null;
    if (containerLog.isTraceEnabled())
        containerLog.trace("  getRoles(" + dn + ")");
    // Start with roles retrieved from the user entry
    List<String> list = new ArrayList<>();
    List<String> userRoles = user.getRoles();
    if (userRoles != null) {
        list.addAll(userRoles);
    }
    if (commonRole != null)
        list.add(commonRole);
    if (containerLog.isTraceEnabled()) {
        containerLog.trace("  Found " + list.size() + " user internal roles");
        containerLog.trace("  Found user internal roles " + list.toString());
    }
    // Are we configured to do role searches?
    if ((roleFormat == null) || (roleName == null))
        return list;
    // Set up parameters for an appropriate search
    String filter = roleFormat.format(new String[] { doRFC2254Encoding(dn), username, userRoleId });
    SearchControls controls = new SearchControls();
    if (roleSubtree)
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    else
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    controls.setReturningAttributes(new String[] { roleName });
    String base = null;
    if (roleBaseFormat != null) {
        NameParser np = context.getNameParser("");
        Name name = np.parse(dn);
        String[] nameParts = new String[name.size()];
        for (int i = 0; i < name.size(); i++) {
            nameParts[i] = name.get(i);
        }
        base = roleBaseFormat.format(nameParts);
    } else {
        base = "";
    }
    // Perform the configured search and process the results
    NamingEnumeration<SearchResult> results = searchAsUser(context, user, base, filter, controls, isRoleSearchAsUser());
    if (results == null)
        // Should never happen, but just in case ...
        return list;
    HashMap<String, String> groupMap = new HashMap<>();
    try {
        while (results.hasMore()) {
            SearchResult result = results.next();
            Attributes attrs = result.getAttributes();
            if (attrs == null)
                continue;
            String dname = getDistinguishedName(context, roleBase, result);
            String name = getAttributeValue(roleName, attrs);
            if (name != null && dname != null) {
                groupMap.put(dname, name);
            }
        }
    } catch (PartialResultException ex) {
        if (!adCompat)
            throw ex;
    } finally {
        results.close();
    }
    if (containerLog.isTraceEnabled()) {
        Set<Entry<String, String>> entries = groupMap.entrySet();
        containerLog.trace("  Found " + entries.size() + " direct roles");
        for (Entry<String, String> entry : entries) {
            containerLog.trace("  Found direct role " + entry.getKey() + " -> " + entry.getValue());
        }
    }
    // if nested group search is enabled, perform searches for nested groups until no new group is found
    if (getRoleNested()) {
        // The following efficient algorithm is known as memberOf Algorithm, as described in "Practices in
        // Directory Groups". It avoids group slurping and handles cyclic group memberships as well.
        // See http://middleware.internet2.edu/dir/ for details
        Map<String, String> newGroups = new HashMap<>(groupMap);
        while (!newGroups.isEmpty()) {
            // Stores the groups we find in this iteration
            Map<String, String> newThisRound = new HashMap<>();
            for (Entry<String, String> group : newGroups.entrySet()) {
                filter = roleFormat.format(new String[] { group.getKey(), group.getValue(), group.getValue() });
                if (containerLog.isTraceEnabled()) {
                    containerLog.trace("Perform a nested group search with base " + roleBase + " and filter " + filter);
                }
                results = searchAsUser(context, user, roleBase, filter, controls, isRoleSearchAsUser());
                try {
                    while (results.hasMore()) {
                        SearchResult result = results.next();
                        Attributes attrs = result.getAttributes();
                        if (attrs == null)
                            continue;
                        String dname = getDistinguishedName(context, roleBase, result);
                        String name = getAttributeValue(roleName, attrs);
                        if (name != null && dname != null && !groupMap.keySet().contains(dname)) {
                            groupMap.put(dname, name);
                            newThisRound.put(dname, name);
                            if (containerLog.isTraceEnabled()) {
                                containerLog.trace("  Found nested role " + dname + " -> " + name);
                            }
                        }
                    }
                } catch (PartialResultException ex) {
                    if (!adCompat)
                        throw ex;
                } finally {
                    results.close();
                }
            }
            newGroups = newThisRound;
        }
    }
    list.addAll(groupMap.values());
    return list;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) PartialResultException(javax.naming.PartialResultException) CompositeName(javax.naming.CompositeName) Name(javax.naming.Name) Entry(java.util.Map.Entry) SearchControls(javax.naming.directory.SearchControls) NameParser(javax.naming.NameParser)

Example 4 with Attributes

use of javax.naming.directory.Attributes in project zeppelin by apache.

the class LdapGroupRealm method getRoleNamesForUser.

public Set<String> getRoleNamesForUser(String username, LdapContext ldapContext, String userDnTemplate) throws NamingException {
    try {
        Set<String> roleNames = new LinkedHashSet<>();
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchFilter = "(&(objectClass=groupOfNames)(member=" + userDnTemplate + "))";
        Object[] searchArguments = new Object[] { username };
        NamingEnumeration<?> answer = ldapContext.search(String.valueOf(ldapContext.getEnvironment().get("ldap.searchBase")), searchFilter, searchArguments, searchCtls);
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            if (attrs != null) {
                NamingEnumeration<?> ae = attrs.getAll();
                while (ae.hasMore()) {
                    Attribute attr = (Attribute) ae.next();
                    if (attr.getID().equals("cn")) {
                        roleNames.add((String) attr.get());
                    }
                }
            }
        }
        return roleNames;
    } catch (Exception e) {
        LOG.error("Error", e);
    }
    return new HashSet<>();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Attribute(javax.naming.directory.Attribute) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 5 with Attributes

use of javax.naming.directory.Attributes in project zeppelin by apache.

the class GetUserList method getUserList.

/**
   * function to extract users from LDAP
   */
public List<String> getUserList(JndiLdapRealm r, String searchText) {
    List<String> userList = new ArrayList<>();
    String userDnTemplate = r.getUserDnTemplate();
    String[] userDn = userDnTemplate.split(",", 2);
    String userDnPrefix = userDn[0].split("=")[0];
    String userDnSuffix = userDn[1];
    JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
    try {
        LdapContext ctx = CF.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { userDnPrefix };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)", constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userDnPrefix) != null) {
                String currentUser = attrs.get(userDnPrefix).toString();
                userList.add(currentUser.split(":")[1].trim());
            }
        }
    } catch (Exception e) {
        LOG.error("Error retrieving User list from Ldap Realm", e);
    }
    LOG.info("UserList: " + userList);
    return userList;
}
Also used : ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult) LdapContext(javax.naming.ldap.LdapContext) JndiLdapContextFactory(org.apache.shiro.realm.ldap.JndiLdapContextFactory)

Aggregations

Attributes (javax.naming.directory.Attributes)249 Attribute (javax.naming.directory.Attribute)134 SearchResult (javax.naming.directory.SearchResult)84 NamingException (javax.naming.NamingException)82 BasicAttributes (javax.naming.directory.BasicAttributes)72 ArrayList (java.util.ArrayList)58 BasicAttribute (javax.naming.directory.BasicAttribute)56 SearchControls (javax.naming.directory.SearchControls)52 DirContext (javax.naming.directory.DirContext)49 NamingEnumeration (javax.naming.NamingEnumeration)45 Test (org.junit.Test)34 InitialDirContext (javax.naming.directory.InitialDirContext)32 LdapContext (javax.naming.ldap.LdapContext)27 HashMap (java.util.HashMap)25 InitialLdapContext (javax.naming.ldap.InitialLdapContext)24 Hashtable (java.util.Hashtable)20 HashSet (java.util.HashSet)18 Map (java.util.Map)17 IOException (java.io.IOException)16 Identity (org.olat.core.id.Identity)16