Search in sources :

Example 36 with SearchControls

use of javax.naming.directory.SearchControls in project uPortal by Jasig.

the class LDAPGroupStore method searchForEntities.

public EntityIdentifier[] searchForEntities(String query, SearchMethod method, Class type) throws GroupsException {
    if (type != group && type != iperson)
        return new EntityIdentifier[0];
    // Guarantee that LDAP injection is prevented by replacing LDAP special characters
    // with escaped versions of the character
    query = LdapEncoder.filterEncode(query);
    ArrayList ids = new ArrayList();
    switch(method) {
        case STARTS_WITH:
        case STARTS_WITH_CI:
            query = query + "*";
            break;
        case ENDS_WITH:
        case ENDS_WITH_CI:
            query = "*" + query;
            break;
        case CONTAINS:
        case CONTAINS_CI:
            query = "*" + query + "*";
            break;
        case DISCRETE:
        case DISCRETE_CI:
    }
    query = namefield + "=" + query;
    DirContext context = getConnection();
    NamingEnumeration userlist = null;
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { keyfield });
    try {
        userlist = context.search(usercontext, query, sc);
        ArrayList keys = new ArrayList();
        processLdapResults(userlist, keys);
        String[] k = (String[]) keys.toArray(new String[0]);
        for (int i = 0; i < k.length; i++) {
            ids.add(new EntityIdentifier(k[i], iperson));
        }
        return (EntityIdentifier[]) ids.toArray(new EntityIdentifier[0]);
    } catch (NamingException nex) {
        throw new GroupsException("LDAPGroupStore: Unable to perform filter " + query, nex);
    }
}
Also used : GroupsException(org.apereo.portal.groups.GroupsException) ArrayList(java.util.ArrayList) NamingEnumeration(javax.naming.NamingEnumeration) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) EntityIdentifier(org.apereo.portal.EntityIdentifier)

Example 37 with SearchControls

use of javax.naming.directory.SearchControls in project uPortal by Jasig.

the class SimpleLdapSecurityContext method authenticate.

/**
 * Authenticates the user.
 */
public synchronized void authenticate() throws PortalSecurityException {
    this.isauth = false;
    ILdapServer ldapConn;
    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 38 with SearchControls

use of javax.naming.directory.SearchControls in project opentheso by miledrousset.

the class LDAPAuthenticator method dnFromUser.

private String dnFromUser(String username) throws NamingException {
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, "ldap://ldap.mondomaine.fr");
    props.put(Context.REFERRAL, "ignore");
    InitialDirContext context = new InitialDirContext(props);
    SearchControls ctrls = new SearchControls();
    ctrls.setReturningAttributes(new String[] { authBean.getFirstnameLdap(), authBean.getNameLdap() });
    ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration<SearchResult> answers = context.search(authBean.getScope(), "(" + authBean.getUidLdap() + "=" + username + ")", ctrls);
    if (answers != null) {
        SearchResult result = answers.next();
        return result.getNameInNamespace();
    }
    return null;
}
Also used : SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) InitialDirContext(javax.naming.directory.InitialDirContext) Properties(java.util.Properties)

Example 39 with SearchControls

use of javax.naming.directory.SearchControls in project opentheso by miledrousset.

the class LDAPAuthenticator method login.

/* (non-Javadoc)
     * @see fr.persee.aldo.auth.Authenticator#login(java.lang.String, java.lang.String)
     */
public Account login(String login, String password) {
    Account acc = null;
    try {
        String dn = dnFromUser(login);
        if (dn == null) {
            // TODO gerer exception
            return null;
        }
        env.put(Context.SECURITY_PRINCIPAL, dn);
        env.put(Context.SECURITY_CREDENTIALS, password);
        InitialDirContext context = new InitialDirContext(env);
        SearchControls ctrls = new SearchControls();
        ctrls.setReturningAttributes(new String[] { authBean.getFirstnameLdap(), authBean.getNameLdap(), authBean.getMailLdap() });
        ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration<SearchResult> answers;
        answers = context.search(authBean.getScope(), "(" + authBean.getUidLdap() + "=" + login + ")", ctrls);
        SearchResult result;
        result = answers.next();
        // System.out.println();
        String firstname = result.getAttributes().get(authBean.getFirstnameLdap()).get().toString();
        String name = result.getAttributes().get(authBean.getNameLdap()).get().toString();
        String mail = result.getAttributes().get(authBean.getMailLdap()).get().toString();
        // User
        User user = new User();
        user.setUser(login);
        user.setFirstname(firstname);
        user.setLastname(name);
        user.setMail(mail);
        user.setUid(login);
        // Account
        acc = new Account();
        acc.setBaseId(authBean.getBaseId());
        acc.setUser(user);
    } catch (NamingException e) {
    }
    return acc;
}
Also used : Account(mom.trd.opentheso.bdd.account.Account) User(mom.trd.opentheso.bdd.account.User) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 40 with SearchControls

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

the class LDAPRealm method groupSearch.

/**
 * Search for group membership using the given connection.
 */
private List groupSearch(DirContext ctx, String baseDN, String filter, String target) {
    List groupList = new ArrayList();
    try {
        String[] targets = new String[1];
        targets[0] = target;
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(targets);
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration e = ctx.search(baseDN, filter.replaceAll(Matcher.quoteReplacement("\\"), Matcher.quoteReplacement("\\\\")), ctls);
        while (e.hasMore()) {
            SearchResult res = (SearchResult) e.next();
            Attribute grpAttr = res.getAttributes().get(target);
            int sz = grpAttr.size();
            for (int i = 0; i < sz; i++) {
                String s = (String) grpAttr.get(i);
                groupList.add(s);
            }
        }
    } catch (Exception e) {
        _logger.log(Level.WARNING, "ldaprealm.searcherror", filter);
        _logger.log(Level.WARNING, "security.exception", e);
    }
    return groupList;
}
Also used : Attribute(javax.naming.directory.Attribute) SearchControls(javax.naming.directory.SearchControls) NamingEnumeration(javax.naming.NamingEnumeration) SearchResult(javax.naming.directory.SearchResult) 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)

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