Search in sources :

Example 61 with SearchResult

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

the class ActiveDirectoryGroupRealm method searchForUserName.

public List<String> searchForUserName(String containString, LdapContext ldapContext) throws NamingException {
    List<String> userNameList = new ArrayList<>();
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String searchFilter = "(&(objectClass=*)(userPrincipalName=*" + containString + "*))";
    Object[] searchArguments = new Object[] { containString };
    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);
    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();
        if (log.isDebugEnabled()) {
            log.debug("Retrieving userprincipalname 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().toLowerCase().equals("cn")) {
                    userNameList.addAll(LdapUtils.getAllAttributeValues(attr));
                }
            }
        }
    }
    return userNameList;
}
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)

Example 62 with SearchResult

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

the class LdapRealm method getUserDn.

/**
  * Returns the LDAP User Distinguished Name (DN) to use when acquiring an
  * {@link javax.naming.ldap.LdapContext LdapContext} from the
  * {@link LdapContextFactory}.
  * <p/>
  * If the the {@link #getUserDnTemplate() userDnTemplate} property has been
  * set, this implementation will construct the User DN by substituting the
  * specified {@code principal} into the configured template. If the
  * {@link #getUserDnTemplate() userDnTemplate} has not been set, the method
  * argument will be returned directly (indicating that the submitted
  * authentication token principal <em>is</em> the User DN).
  *
  * @param principal
  *            the principal to substitute into the configured
  *            {@link #getUserDnTemplate() userDnTemplate}.
  * @return the constructed User DN to use at runtime when acquiring an
  *         {@link javax.naming.ldap.LdapContext}.
  * @throws IllegalArgumentException
  *             if the method argument is null or empty
  * @throws IllegalStateException
  *             if the {@link #getUserDnTemplate userDnTemplate} has not been
  *             set.
  * @see LdapContextFactory#getLdapContext(Object, Object)
  */
@Override
protected String getUserDn(final String principal) throws IllegalArgumentException, IllegalStateException {
    String userDn;
    Matcher matchedPrincipal = matchPrincipal(principal);
    String userSearchBase = getUserSearchBase();
    String userSearchAttributeName = getUserSearchAttributeName();
    // If not searching use the userDnTemplate and return.
    if ((userSearchBase == null || userSearchBase.isEmpty()) || (userSearchAttributeName == null && userSearchFilter == null && !"object".equalsIgnoreCase(userSearchScope))) {
        userDn = expandTemplate(userDnTemplate, matchedPrincipal);
        if (log.isDebugEnabled()) {
            log.debug("LDAP UserDN and Principal: " + userDn + "," + principal);
        }
        return userDn;
    }
    // Create the searchBase and searchFilter from config.
    String searchBase = expandTemplate(getUserSearchBase(), matchedPrincipal);
    String searchFilter = null;
    if (userSearchFilter == null) {
        if (userSearchAttributeName == null) {
            searchFilter = String.format("(objectclass=%1$s)", getUserObjectClass());
        } else {
            searchFilter = String.format("(&(objectclass=%1$s)(%2$s=%3$s))", getUserObjectClass(), userSearchAttributeName, expandTemplate(getUserSearchAttributeTemplate(), matchedPrincipal));
        }
    } else {
        searchFilter = expandTemplate(userSearchFilter, matchedPrincipal);
    }
    SearchControls searchControls = getUserSearchControls();
    // Search for userDn and return.
    LdapContext systemLdapCtx = null;
    NamingEnumeration<SearchResult> searchResultEnum = null;
    try {
        systemLdapCtx = getContextFactory().getSystemLdapContext();
        if (log.isDebugEnabled()) {
            log.debug("SearchBase,SearchFilter,UserSearchScope: " + searchBase + "," + searchFilter + "," + userSearchScope);
        }
        searchResultEnum = systemLdapCtx.search(searchBase, searchFilter, searchControls);
        // SearchResults contains all the entries in search scope
        if (searchResultEnum.hasMore()) {
            SearchResult searchResult = searchResultEnum.next();
            userDn = searchResult.getNameInNamespace();
            if (log.isDebugEnabled()) {
                log.debug("UserDN Returned,Principal: " + userDn + "," + principal);
            }
            return userDn;
        } else {
            throw new IllegalArgumentException("Illegal principal name: " + principal);
        }
    } catch (AuthenticationException ne) {
        ne.printStackTrace();
        throw new IllegalArgumentException("Illegal principal name: " + principal);
    } catch (NamingException ne) {
        throw new IllegalArgumentException("Hit NamingException: " + ne.getMessage());
    } finally {
        try {
            if (searchResultEnum != null) {
                searchResultEnum.close();
            }
        } catch (NamingException ne) {
        // Ignore exception on close.
        } finally {
            LdapUtils.closeContext(systemLdapCtx);
        }
    }
}
Also used : Matcher(java.util.regex.Matcher) HashedCredentialsMatcher(org.apache.shiro.authc.credential.HashedCredentialsMatcher) AuthenticationException(javax.naming.AuthenticationException) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) LdapContext(javax.naming.ldap.LdapContext)

Example 63 with SearchResult

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

the class GetUserList method getUserList.

/**
   * function to extract users from Zeppelin LdapRealm
   */
public List<String> getUserList(LdapRealm r, String searchText) {
    List<String> userList = new ArrayList<>();
    if (LOG.isDebugEnabled()) {
        LOG.debug("SearchText: " + searchText);
    }
    String userAttribute = r.getUserSearchAttributeName();
    String userSearchRealm = r.getUserSearchBase();
    String userObjectClass = r.getUserObjectClass();
    JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
    try {
        LdapContext ctx = CF.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { userAttribute };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userSearchRealm, "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=" + searchText + "))", constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userAttribute) != null) {
                String currentUser;
                if (r.getUserLowerCase()) {
                    LOG.debug("userLowerCase true");
                    currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase();
                } else {
                    LOG.debug("userLowerCase false");
                    currentUser = (String) attrs.get(userAttribute).get();
                }
                if (LOG.isDebugEnabled()) {
                    LOG.debug("CurrentUser: " + currentUser);
                }
                userList.add(currentUser.trim());
            }
        }
    } catch (Exception e) {
        LOG.error("Error retrieving User list from Ldap Realm", e);
    }
    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)

Example 64 with SearchResult

use of javax.naming.directory.SearchResult in project hive by apache.

the class LdapTestUtils method mockSearchResult.

public static SearchResult mockSearchResult(String dn, Attributes attributes) {
    SearchResult searchResult = mock(SearchResult.class);
    when(searchResult.getNameInNamespace()).thenReturn(dn);
    when(searchResult.getAttributes()).thenReturn(attributes);
    return searchResult;
}
Also used : SearchResult(javax.naming.directory.SearchResult)

Example 65 with SearchResult

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

the class LdapLoginModule method bindingLogin.

/**
     * binding authentication check
     * This method of authentication works only if the user branch of the DIT (ldap tree)
     * has an ACI (access control instruction) that allow the access to any user or at least
     * for the user that logs in.
     *
     * @param username the user name
     * @param password the password
     * @return true always
     * @throws LoginException if unable to bind the login
     * @throws NamingException if failure to bind login
     */
public boolean bindingLogin(String username, Object password) throws LoginException, NamingException {
    SearchResult searchResult = findUser(username);
    String userDn = searchResult.getNameInNamespace();
    LOG.info("Attempting authentication: " + userDn);
    Hashtable<Object, Object> environment = getEnvironment();
    if (userDn == null || "".equals(userDn)) {
        throw new NamingException("username may not be empty");
    }
    environment.put(Context.SECURITY_PRINCIPAL, userDn);
    // RFC 4513 section 6.3.1, protect against ldap server implementations that allow successful binding on empty passwords
    if (password == null || "".equals(password)) {
        throw new NamingException("password may not be empty");
    }
    environment.put(Context.SECURITY_CREDENTIALS, password);
    DirContext dirContext = new InitialDirContext(environment);
    List<String> roles = getUserRolesByDn(dirContext, userDn);
    UserInfo userInfo = new UserInfo(username, null, roles);
    setCurrentUser(new JAASUserInfo(userInfo));
    setAuthenticated(true);
    return true;
}
Also used : SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext)

Aggregations

SearchResult (javax.naming.directory.SearchResult)95 SearchControls (javax.naming.directory.SearchControls)63 NamingException (javax.naming.NamingException)43 Attributes (javax.naming.directory.Attributes)35 Attribute (javax.naming.directory.Attribute)32 ArrayList (java.util.ArrayList)29 DirContext (javax.naming.directory.DirContext)27 NamingEnumeration (javax.naming.NamingEnumeration)24 InitialDirContext (javax.naming.directory.InitialDirContext)16 Test (org.junit.Test)15 LdapContext (javax.naming.ldap.LdapContext)13 IOException (java.io.IOException)9 BasicAttributes (javax.naming.directory.BasicAttributes)9 DistinguishedName (org.springframework.ldap.core.DistinguishedName)9 DirContextAdapter (org.springframework.ldap.core.DirContextAdapter)7 HashMap (java.util.HashMap)6 HashSet (java.util.HashSet)6 Name (javax.naming.Name)6 BasicAttribute (javax.naming.directory.BasicAttribute)6 PartialResultException (javax.naming.PartialResultException)5