Example usage for javax.naming.ldap LdapContext search

List of usage examples for javax.naming.ldap LdapContext search

Introduction

In this page you can find the example usage for javax.naming.ldap LdapContext search.

Prototype

public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes,
        String[] attributesToReturn) throws NamingException;

Source Link

Document

Searches in a single context for objects that contain a specified set of attributes, and retrieves selected attributes.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String url = "ldap://localhost/o=JNDITutorial";
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "userDN");
    env.put(Context.SECURITY_CREDENTIALS, "secret");

    LdapContext ctx = new InitialLdapContext(env, null);

    NamingEnumeration answer = ctx.search("ou=People", "(cn=*)", null);

    System.out.println(ctx.getResponseControls());

    while (answer.hasMore()) {
        SearchResult si = (SearchResult) answer.next();
        if (si instanceof HasControls) {
            System.out.println(((HasControls) si).getControls());
        }/*from   w  w  w . ja  va 2  s .  co  m*/
    }
    System.out.println(ctx.getResponseControls());
}

From source file:SortedResults.java

public static void main(String[] args) throws IOException {

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/ou=People,o=JNDITutorial");

    try {/*from w  w  w  .j  ava 2  s . c om*/
        // Create initial context with no connection request controls
        LdapContext ctx = new InitialLdapContext(env, null);

        // Create a sort control that sorts based on CN
        String sortKey = "cn";
        ctx.setRequestControls(new Control[] { new SortControl(sortKey, Control.CRITICAL) });

        // Perform a search
        NamingEnumeration results = ctx.search("", "(objectclass=*)", new SearchControls());

        // Iterate over search results
        System.out.println("---->sort by cn");
        while (results != null && results.hasMore()) {
            // Display an entry
            SearchResult entry = (SearchResult) results.next();
            System.out.println(entry.getName());

            // Handle the entry's response controls (if any)
            if (entry instanceof HasControls) {
                // ((HasControls)entry).getControls();
            }
        }
        // Examine the sort control response
        Control[] controls = ctx.getResponseControls();
        if (controls != null) {
            for (int i = 0; i < controls.length; i++) {
                if (controls[i] instanceof SortResponseControl) {
                    SortResponseControl src = (SortResponseControl) controls[i];
                    if (!src.isSorted()) {
                        throw src.getException();
                    }
                } else {
                    // Handle other response controls (if any)
                }
            }
        }

        // Close when no longer needed
        ctx.close();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:ManageReferral.java

public static void main(String[] args) {

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:489/o=JNDITutorial");
    // env.put(Context.REFERRAL, "follow");
    env.put(Context.REFERRAL, "ignore");

    try {/*  w  w w  .ja  v  a2  s  .  c  o  m*/
        // Create initial context
        LdapContext ctx = (LdapContext) new InitialLdapContext(env, null);
        // ctx.setRequestControls(new Control[] {
        // new ManageReferralControl() });

        // Set controls for performing subtree search
        SearchControls ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // Perform search
        NamingEnumeration answer = ctx.search("", "(objectclass=*)", ctls);

        // Print the answer
        while (answer.hasMore()) {
            System.out.println(">>>" + ((SearchResult) answer.next()).getName());
        }

        // Close the context when we're done
        ctx.close();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:PagedSearch.java

public static void main(String[] args) {

    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    /* Specify host and port to use for directory service */
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/ou=People,o=JNDITutorial");

    try {//w  w w  .j  a  v  a  2 s . co m
        LdapContext ctx = new InitialLdapContext(env, null);

        // Activate paged results
        int pageSize = 5;
        byte[] cookie = null;
        ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        int total;

        do {
            /* perform the search */
            NamingEnumeration results = ctx.search("", "(objectclass=*)", new SearchControls());

            /* for each entry print out name + all attrs and values */
            while (results != null && results.hasMore()) {
                SearchResult entry = (SearchResult) results.next();
                System.out.println(entry.getName());
            }

            // Examine the paged results control response
            Control[] controls = ctx.getResponseControls();
            if (controls != null) {
                for (int i = 0; i < controls.length; i++) {
                    if (controls[i] instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                        total = prrc.getResultSize();
                        if (total != 0) {
                            System.out.println("(total : " + total);
                        } else {
                            System.out.println("(total: unknown)");
                        }
                        cookie = prrc.getCookie();
                    }
                }
            } else {
                System.out.println("No controls were sent from the server");
            }
            ctx.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

        } while (cookie != null);

        ctx.close();

    } catch (NamingException e) {
        System.err.println("PagedSearch failed.");
        e.printStackTrace();
    } catch (IOException ie) {
        System.err.println("PagedSearch failed.");
        ie.printStackTrace();
    }
}

From source file:PagedSearch.java

public static void main(String[] args) {

    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    /* Specify host and port to use for directory service */
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/ou=People,o=JNDITutorial");

    try {/*from   ww w.j  av a 2 s.c o m*/
        LdapContext ctx = new InitialLdapContext(env, null);

        // Activate paged results
        int pageSize = 5;
        byte[] cookie = null;
        ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        int total;

        do {
            /* perform the search */
            NamingEnumeration results = ctx.search("", "(objectclass=*)", new SearchControls());

            /* for each entry print out name + all attrs and values */
            while (results != null && results.hasMore()) {
                SearchResult entry = (SearchResult) results.next();
                System.out.println(entry.getName());
            }

            // Examine the paged results control response
            Control[] controls = ctx.getResponseControls();
            if (controls != null) {
                for (int i = 0; i < controls.length; i++) {
                    if (controls[i] instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                        total = prrc.getResultSize();
                        if (total != 0) {
                            System.out.println("***************** END-OF-PAGE " + "(total : " + total
                                    + ") *****************\n");
                        } else {
                            System.out.println(
                                    "***************** END-OF-PAGE " + "(total: unknown) ***************\n");
                        }
                        cookie = prrc.getCookie();
                    }
                }
            } else {
                System.out.println("No controls were sent from the server");
            }
            // Re-activate paged results
            ctx.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

        } while (cookie != null);

        ctx.close();

    } catch (NamingException e) {
        System.err.println("PagedSearch failed.");
        e.printStackTrace();
    } catch (IOException ie) {
        System.err.println("PagedSearch failed.");
        ie.printStackTrace();
    }
}

From source file:jp.ikedam.jenkins.plugins.ldap_sasl.SearchGroupResolver.java

/**
 * Resolves groups by querying the LDAP directory. 
 * /*ww w .  j  a v  a2  s.c  o  m*/
 * Never return null in any case. Returns empty list instead.
 * 
 * @param ctx
 * @param dn
 * @param username
 * @return List of authorities (not null)
 * @see jp.ikedam.jenkins.plugins.ldap_sasl.GroupResolver#resolveGroup(javax.naming.ldap.LdapContext, java.lang.String, java.lang.String)
 */
@Override
public List<GrantedAuthority> resolveGroup(LdapContext ctx, String dn, String username) {
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    Logger logger = getLogger();

    if (dn == null) {
        logger.warning("Group cannot be resolved: DN of the user is not resolved!");
        return authorities;
    }

    try {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        logger.fine(String.format("Searching groups base=%s, dn=%s", getSearchBase(), dn));
        NamingEnumeration<SearchResult> entries = ctx.search((getSearchBase() != null) ? getSearchBase() : "",
                getGroupSearchQuery(dn), searchControls);
        while (entries.hasMore()) {
            SearchResult entry = entries.next();
            String groupName = entry.getAttributes().get("cn").get().toString();
            if (getPrefix() != null) {
                groupName = getPrefix() + groupName;
            }
            authorities.add(new GrantedAuthorityImpl(groupName));
            logger.fine(String.format("group: %s", groupName));
        }
        entries.close();
    } catch (NamingException e) {
        logger.log(Level.WARNING, "Failed to search groups", e);
    }

    return authorities;
}

From source file:jp.ikedam.jenkins.plugins.ldap_sasl.SearchUserDnResolver.java

/**
 * Resolve the user DN by querying the LDAP directory.
 * //from w  ww  .j  a v a2s .  c o m
 * @param ctx LDAP context, already authenticated.
 * @param username the username the user authenticated with.
 * 
 * @return the DN of the user.
 * @see jp.ikedam.jenkins.plugins.ldap_sasl.UserDnResolver#getUserDn(javax.naming.ldap.LdapContext, java.lang.String)
 */
@Override
public String getUserDn(LdapContext ctx, String username) {
    Logger logger = getLogger();
    if (StringUtils.isBlank(getSearchQueryTemplate())) {
        // not configured.
        logger.severe("Not configured.");

        return null;
    }

    try {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        logger.fine(String.format("Searching users base=%s, username=%s", getSearchBase(), username));
        String query = expandUsername(getSearchQueryTemplate(), username);
        NamingEnumeration<SearchResult> entries = ctx.search((getSearchBase() != null) ? getSearchBase() : "",
                query, searchControls);
        if (!entries.hasMore()) {
            // no entry.
            logger.severe(String.format("User not found: %s", username));
            return null;
        }

        String userDn = entries.next().getNameInNamespace();

        if (entries.hasMore()) {
            // more than one entry.
            logger.severe(String.format("User found more than one: %s", username));
            return null;
        }
        entries.close();

        return userDn;
    } catch (NamingException e) {
        logger.log(Level.SEVERE, "Failed to search a user", e);
        return null;
    }
}

From source file:com.wfp.utils.LDAPUtils.java

/**
 * Used to search the LDAP based on the follwoing argumets
 * @param ldapCtx/*  ww w.ja  va  2 s  .  c  om*/
 * @param searchCtls
 * @param searchFilter
 * @param searchBase
 * @return
 * @throws NamingException
 */
@SuppressWarnings("unchecked")
public static NamingEnumeration getSearchResults(LdapContext ldapCtx, SearchControls searchCtls,
        String searchFilter, String searchBase) {
    try {
        // Search for objects using the filter
        try {
            return ldapCtx.search(searchBase, searchFilter, searchCtls);
        } catch (NamingException e) {
            Logger.error(
                    "Error occured while searching results : 249: getSearchResults(LdapContext ldapCtx, SearchControls searchCtls, String searchFilter, String searchBase)["
                            + e.getLocalizedMessage() + "]",
                    LDAPUtils.class);
        }
    } finally {
        if (ldapCtx != null) {
            try {
                ldapCtx.close();
            } catch (NamingException e) {
                Logger.error(
                        "Error occured while closing the connection to LDAP [" + e.getLocalizedMessage() + "]",
                        LDAPUtils.class);
            }
        }
    }
    return null;
}

From source file:com.liferay.portal.action.LoginAction.java

public static void login(HttpServletRequest req, HttpServletResponse res, String login, String password,
        boolean rememberMe) throws Exception {

    CookieKeys.validateSupportCookie(req);

    HttpSession ses = req.getSession();//from w  w  w  .j ava2 s . c  om

    long userId = GetterUtil.getLong(login);

    int authResult = Authenticator.FAILURE;

    Company company = PortalUtil.getCompany(req);

    //
    boolean ldaplogin = false;
    if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) {
        LdapContext ctx = PortalLDAPUtil.getContext(company.getCompanyId());
        String accountname = "";
        try {
            User user1 = UserLocalServiceUtil.getUserByScreenName(company.getCompanyId(), login);
            Properties env = new Properties();

            String baseProviderURL = PrefsPropsUtil.getString(company.getCompanyId(),
                    PropsUtil.LDAP_BASE_PROVIDER_URL);
            String userDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_USERS_DN);
            String baseDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_BASE_DN);
            String filter = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_SEARCH_FILTER);
            filter = StringUtil.replace(filter,
                    new String[] { "@company_id@", "@email_address@", "@screen_name@", "@user_id@" },
                    new String[] { String.valueOf(company.getCompanyId()), "", login, login });
            try {
                SearchControls cons = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, null, false,
                        false);

                NamingEnumeration enu = ctx.search(userDN, filter, cons);
                if (enu.hasMoreElements()) {
                    SearchResult result = (SearchResult) enu.nextElement();
                    accountname = result.getName();
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }

            env.put(Context.INITIAL_CONTEXT_FACTORY, PrefsPropsUtil.getString(PropsUtil.LDAP_FACTORY_INITIAL));
            env.put(Context.PROVIDER_URL, LDAPUtil.getFullProviderURL(baseProviderURL, baseDN));
            env.put(Context.SECURITY_PRINCIPAL, accountname + "," + userDN);
            env.put(Context.SECURITY_CREDENTIALS, password);

            new InitialLdapContext(env, null);
            ldaplogin = true;
            System.out.println("LDAP Login");
        } catch (Exception e) {
            SessionErrors.add(req, "ldapAuthentication");
            e.printStackTrace();
            System.out.println("LDAP error login");
            return;
        }
    }

    //

    Map headerMap = new HashMap();

    Enumeration enu1 = req.getHeaderNames();

    while (enu1.hasMoreElements()) {
        String name = (String) enu1.nextElement();

        Enumeration enu2 = req.getHeaders(name);

        List headers = new ArrayList();

        while (enu2.hasMoreElements()) {
            String value = (String) enu2.nextElement();

            headers.add(value);
        }

        headerMap.put(name, (String[]) headers.toArray(new String[0]));
    }

    Map parameterMap = req.getParameterMap();

    if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_EA)) {
        authResult = UserLocalServiceUtil.authenticateByEmailAddress(company.getCompanyId(), login, password,
                headerMap, parameterMap);

        userId = UserLocalServiceUtil.getUserIdByEmailAddress(company.getCompanyId(), login);
    } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_SN)) {
        authResult = UserLocalServiceUtil.authenticateByScreenName(company.getCompanyId(), login, password,
                headerMap, parameterMap);

        userId = UserLocalServiceUtil.getUserIdByScreenName(company.getCompanyId(), login);
    } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_ID)) {
        authResult = UserLocalServiceUtil.authenticateByUserId(company.getCompanyId(), userId, password,
                headerMap, parameterMap);
    }

    boolean OTPAuth = false;

    if (GetterUtil.getBoolean(PropsUtil.get("use.yubicoauthentication"), false) == true) {
        String otppasswd = ParamUtil.getString(req, "otp");
        String userslist = GetterUtil.getString(PropsUtil.get("yubico.users.not.require.otp"), "root");
        if (userslist.contains(login)) {
            authResult = Authenticator.SUCCESS;
        } else {
            OTPAuth = SecurityUtils.verifyOTP(otppasswd, login);
            if (authResult == Authenticator.SUCCESS && OTPAuth) {
                authResult = Authenticator.SUCCESS;
            } else {
                authResult = Authenticator.FAILURE;
            }
        }
    }

    if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) {
        if (!login.equals("root")) {
            if (ldaplogin) {
                authResult = Authenticator.SUCCESS;
            }
        }
    }

    if (authResult == Authenticator.SUCCESS) {

        boolean loginViaPortal = true;

        setLoginCookies(req, res, ses, userId, rememberMe);
        // login to epsos
        String language = GeneralUtils.getLocale(req);
        SpiritEhrWsClientInterface webService = EpsosHelperService.getInstance().getWebService(req);

        InitUserObj initUserObj = EpsosHelperImpl.createEpsosUserInformation(req, res, language, webService,
                userId, company.getCompanyId(), login, loginViaPortal);
        SpiritUserClientDto usr = initUserObj.getUsr();
        Assertion assertion = initUserObj.getAssertion();

        if (Validator.isNotNull(usr)) {
            req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTIONID,
                    assertion.getID());
            req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTION, assertion);
            req.getSession().setAttribute(EPSOS_LOGIN_INFORMATION_ATTRIBUTE, usr);
        } else {
            SessionErrors.add(req, "User doesn't belong to epSOS role so you can't login");
        }

        if (Validator.isNull(usr) && (!(login.equals("root")))) {
            try {
                Cookie cookie = new Cookie(CookieKeys.ID, StringPool.BLANK);
                cookie.setMaxAge(0);
                cookie.setPath("/");

                CookieKeys.addCookie(res, cookie);

                cookie = new Cookie(CookieKeys.PASSWORD, StringPool.BLANK);
                cookie.setMaxAge(0);
                cookie.setPath("/");

                CookieKeys.addCookie(res, cookie);

                try {
                    ses.invalidate();
                } catch (Exception e) {
                }

            } catch (Exception e) {
                req.setAttribute(PageContext.EXCEPTION, e);

            }
            throw new AuthException();

        }

    } else {
        throw new AuthException();
    }
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Gets the LDAP users/*from   www  . j  a  va2  s .c  o m*/
 * 
 * @param ctx
 * @param loginAttributeName
 * @param searchStrs
 * @return
 */
static List<TPersonBean> getLdapUsers(LdapContext ctx, String loginAttributeName, List<String> searchStrs) {
    List<TPersonBean> personBeans = new LinkedList<TPersonBean>();
    if (ldapMap == null || ldapMap.isEmpty()) {
        LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!");
        return personBeans;
    }
    String firstNameAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.FIRST_NAME);
    String lastNameAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.LAST_NAME);
    String emailAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.EMAIL);
    String phoneAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.PHONE);
    for (String searchStr : searchStrs) {
        LOGGER.debug("Searching by filter " + searchStr);
        SearchControls ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        try {
            NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls);
            while (results != null && results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName,
                        lastNameAttributName, emailAttributeName, phoneAttributName);
                if (personBean != null) {
                    LOGGER.debug("Search successful " + searchStr);
                    personBeans.add(personBean);
                }
            }
        } catch (NamingException e) {
            LOGGER.warn("Search failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return personBeans;
}