Search in sources :

Example 66 with SearchControls

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

the class ActiveDirectoryLoginModule method verifyLoginData.

@Override
protected boolean verifyLoginData() throws FailedLoginException {
    String[] returnedAtts = { authenticationAttribute };
    Encoder encoder = DefaultEncoder.getInstance();
    String requestSearchFilter = searchFilter.replaceAll("%USERNAME%", encoder.encodeForLDAP(getUsername()));
    SearchControls searchCtls = new SearchControls();
    searchCtls.setReturningAttributes(returnedAtts);
    searchCtls.setSearchScope(searchScope);
    Hashtable<String, String> env = getEnv();
    debug("Verifying credentials for user: " + getUsername());
    boolean ldapUser = false;
    String userCN = null;
    try {
        LdapContext ldapContext = getLdapContext(env);
        if (ldapContext != null) {
            NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, requestSearchFilter, searchCtls);
            while (!ldapUser && answer.hasMoreElements()) {
                SearchResult sr = answer.next();
                userCN = sr.getName();
                Attributes attrs = sr.getAttributes();
                if (attrs != null) {
                    NamingEnumeration<? extends Attribute> ne = attrs.getAll();
                    ldapUser = ne.hasMore();
                    ne.close();
                }
            }
            debug("Authentication succeeded");
            if (Boolean.TRUE.equals(GlobalContext.locate(ConfigurationServiceImpl.class).getValue(SimbaConfigurationParameter.ENABLE_AD_GROUPS)) && userCN != null) {
                updateUserGroups(ldapContext, userCN);
            }
        }
        return ldapUser;
    } catch (NamingException ex) {
        debug("Authentication failed");
        throw new FailedLoginException(ex.getMessage());
    }
}
Also used : Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) ConfigurationServiceImpl(org.simbasecurity.core.service.config.ConfigurationServiceImpl) FailedLoginException(javax.security.auth.login.FailedLoginException) Encoder(org.owasp.esapi.Encoder) DefaultEncoder(org.owasp.esapi.reference.DefaultEncoder) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext)

Example 67 with SearchControls

use of javax.naming.directory.SearchControls in project cxf by apache.

the class LdapSearch method searchSubTree.

// CHECKSTYLE:ON
public NamingEnumeration<SearchResult> searchSubTree(String rootEntry, String filter) throws NamingException {
    int retry = 0;
    while (true) {
        try {
            if (this.dirContext == null) {
                this.dirContext = createInitialContext();
            }
            SearchControls ctls = new SearchControls();
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            return dirContext.search(rootEntry, filter, ctls);
        } catch (CommunicationException e) {
            LOG.log(Level.WARNING, "Error in ldap search: " + e.getMessage(), e);
            this.dirContext = null;
            retry++;
            if (retry >= numRetries) {
                throw new XKMSException(ResultMajorEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_RECEIVER, ResultMinorEnum.HTTP_WWW_W_3_ORG_2002_03_XKMS_FAILURE, "Backend failure");
            }
        }
    }
}
Also used : CommunicationException(javax.naming.CommunicationException) XKMSException(org.apache.cxf.xkms.exception.XKMSException) SearchControls(javax.naming.directory.SearchControls)

Example 68 with SearchControls

use of javax.naming.directory.SearchControls in project traccar by tananaev.

the class LdapProvider method lookupUser.

private SearchResult lookupUser(String accountName) throws NamingException {
    InitialDirContext context = initContext();
    String searchString = searchFilter.replace(":login", accountName);
    SearchControls searchControls = new SearchControls();
    String[] attributeFilter = { idAttribute, nameAttribute, mailAttribute };
    searchControls.setReturningAttributes(attributeFilter);
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration<SearchResult> results = context.search(searchBase, searchString, searchControls);
    SearchResult searchResult = null;
    if (results.hasMoreElements()) {
        searchResult = results.nextElement();
        if (results.hasMoreElements()) {
            Log.warning("Matched multiple users for the accountName: " + accountName);
            return null;
        }
    }
    return searchResult;
}
Also used : SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 69 with SearchControls

use of javax.naming.directory.SearchControls in project Payara by payara.

the class LDAPRealm method dynamicGroupSearch.

/**
 * Search for group membership using the given connection.
 */
private List dynamicGroupSearch(DirContext ctx, String baseDN, String memberOfAttr, String filter, String target) throws NamingException {
    List groupList = new ArrayList();
    String[] targets = new String[] { memberOfAttr };
    try {
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(targets);
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        // Set this to false to avoid objects and hence exposing ldap object
        // injection.
        ctls.setReturningObjFlag(false);
        NamingEnumeration e = ctx.search(baseDN, filter, ctls);
        while (e.hasMore()) {
            SearchResult res = (SearchResult) e.next();
            Attribute isMemberOf = res.getAttributes().get(memberOfAttr);
            if (isMemberOf != null) {
                for (Enumeration values = isMemberOf.getAll(); values.hasMoreElements(); ) {
                    String groupDN = (String) values.nextElement();
                    LdapName dn = new LdapName(groupDN);
                    for (Rdn rdn : dn.getRdns()) {
                        if (rdn.getType().equalsIgnoreCase(target)) {
                            groupList.add(rdn.getValue());
                            break;
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        _logger.log(Level.WARNING, "ldaprealm.searcherror", filter);
        _logger.log(Level.WARNING, "security.exception", e);
    }
    return groupList;
}
Also used : NamingEnumeration(javax.naming.NamingEnumeration) Attribute(javax.naming.directory.Attribute) SearchControls(javax.naming.directory.SearchControls) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult) Rdn(javax.naming.ldap.Rdn) LoginException(javax.security.auth.login.LoginException) BadRealmException(com.sun.enterprise.security.auth.realm.BadRealmException) NamingException(javax.naming.NamingException) NoSuchRealmException(com.sun.enterprise.security.auth.realm.NoSuchRealmException) InvalidOperationException(com.sun.enterprise.security.auth.realm.InvalidOperationException) IOException(java.io.IOException) NoSuchUserException(com.sun.enterprise.security.auth.realm.NoSuchUserException) LdapName(javax.naming.ldap.LdapName)

Example 70 with SearchControls

use of javax.naming.directory.SearchControls in project scheduling by ow2-proactive.

the class LDAPLoginModule method getLDAPUserDN.

/**
 * Connects anonymously to the LDAP server <code>url</code> and retrieve
 * DN of the user <code>username</code>
 *
 * <p>
 * @exception NamingException
 *                if a naming exception is encountered.
 * <p>
 *
 * @return the String containing the UID of the user or null if the user is
 *         not found.
 */
private String getLDAPUserDN(String username) throws NamingException {
    String userDN = null;
    DirContext ctx = null;
    try {
        // Create the initial directory context
        ctx = this.connectAndGetContext();
        SearchControls sControl = new SearchControls();
        sControl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String filter = String.format(ldapProperties.getProperty(LDAPProperties.LDAP_USER_FILTER), username);
        // looking for the user dn (distinguish name)
        NamingEnumeration<SearchResult> answer = ctx.search(USERS_DN, filter, sControl);
        if (answer.hasMoreElements()) {
            SearchResult result = (SearchResult) answer.next();
            userDN = result.getNameInNamespace();
            if (logger.isDebugEnabled()) {
                logger.debug("User " + username + " has LDAP entry " + userDN);
            }
            subject.getPrincipals().add(new UserNamePrincipal(username));
            // looking for the user groups
            String groupFilter = String.format(ldapProperties.getProperty(LDAPProperties.LDAP_GROUP_FILTER), userDN);
            NamingEnumeration<SearchResult> groupResults = ctx.search(GROUPS_DN, groupFilter, sControl);
            while (groupResults.hasMoreElements()) {
                SearchResult res = (SearchResult) groupResults.next();
                Attribute attr = res.getAttributes().get(ldapProperties.getProperty(LDAPProperties.LDAP_GROUPNAME_ATTR));
                if (attr != null) {
                    String groupName = attr.get().toString();
                    subject.getPrincipals().add(new GroupNamePrincipal(groupName));
                    if (logger.isDebugEnabled()) {
                        logger.debug("User " + username + " is a member of group " + groupName);
                    }
                }
            }
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("User DN not found");
            }
        }
    } catch (NamingException e) {
        logger.error("Problem with the search in mode: " + AUTHENTICATION_METHOD + e);
        throw e;
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException e) {
            logger.error("", e);
            logger.error("Problem closing LDAP connection: " + e.getMessage());
        }
    }
    return userDN;
}
Also used : UserNamePrincipal(org.ow2.proactive.authentication.principals.UserNamePrincipal) Attribute(javax.naming.directory.Attribute) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) GroupNamePrincipal(org.ow2.proactive.authentication.principals.GroupNamePrincipal)

Aggregations

SearchControls (javax.naming.directory.SearchControls)70 SearchResult (javax.naming.directory.SearchResult)55 NamingException (javax.naming.NamingException)35 ArrayList (java.util.ArrayList)24 NamingEnumeration (javax.naming.NamingEnumeration)21 Attributes (javax.naming.directory.Attributes)21 Attribute (javax.naming.directory.Attribute)19 DirContext (javax.naming.directory.DirContext)15 InitialDirContext (javax.naming.directory.InitialDirContext)14 IOException (java.io.IOException)8 LdapContext (javax.naming.ldap.LdapContext)8 HashMap (java.util.HashMap)5 GroupNotFoundException (org.jivesoftware.openfire.group.GroupNotFoundException)5 UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)5 HashSet (java.util.HashSet)4 LinkedHashSet (java.util.LinkedHashSet)4 Map (java.util.Map)4 PartialResultException (javax.naming.PartialResultException)4 Control (javax.naming.ldap.Control)4 LoginException (javax.security.auth.login.LoginException)4