Example usage for javax.naming.directory SearchResult getName

List of usage examples for javax.naming.directory SearchResult getName

Introduction

In this page you can find the example usage for javax.naming.directory SearchResult getName.

Prototype

public String getName() 

Source Link

Document

Retrieves the name of this binding.

Usage

From source file:SearchTimeLimit.java

public static void printSearchEnumeration(NamingEnumeration srhEnum) {
    int count = 0;
    try {//  w w  w  .  j  a va 2  s .  c o  m
        while (srhEnum.hasMore()) {
            SearchResult sr = (SearchResult) srhEnum.next();
            System.out.println(">>>" + sr.getName());
            ++count;
        }
        System.out.println("number of answers: " + count);
    } catch (TimeLimitExceededException e) {
        System.out.println("search took more than " + timeout + "ms");
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:SearchCountLimit.java

public static void printSearchEnumeration(NamingEnumeration srhEnum) {
    int count = 0;
    try {// www. j a v  a2s.com
        while (srhEnum.hasMore()) {
            SearchResult sr = (SearchResult) srhEnum.next();
            System.out.println(">>>" + sr.getName());
            ++count;
        }
        System.out.println("number of answers: " + count);
    } catch (SizeLimitExceededException e) {
        if (count == expected)
            System.out.println("number of answers: " + count);
        else
            e.printStackTrace();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:edu.lafayette.metadb.model.userman.UserManDAO.java

/**
 * Get the LDAP DN for a user.//ww  w. j a va  2 s . c o m
 * @param searchUser
 * @param searchPassword
 * @param userName
 * @return
 */
@SuppressWarnings("unchecked")
private static String getDN(String searchUser, String searchPassword, String userName) {
    // The resultant DN
    String result;

    // Set up environment for creating initial context
    Hashtable env = new Hashtable(11);
    env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(javax.naming.Context.PROVIDER_URL, Global.LDAP_URL);

    // Use admin credencials for search// Authenticate
    env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple");
    env.put(javax.naming.Context.SECURITY_PRINCIPAL, searchUser);
    env.put(javax.naming.Context.SECURITY_CREDENTIALS, searchPassword);

    DirContext ctx = null;
    try {
        // Create initial context
        ctx = new InitialDirContext(env);
        //MetaDbHelper.note("Created LDAP context");

        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute(Global.LDAP_ID, userName));
        //MetaDbHelper.note("Created attributes");

        // look up attributes
        try {
            //MetaDbHelper.note("Setting up query");

            SearchControls ctrls = new SearchControls();
            ctrls.setSearchScope(Global.LDAP_SCOPE);

            NamingEnumeration<SearchResult> answer = ctx.search(Global.LDAP_URL + Global.LDAP_CONTEXT,
                    "(&({0}={1}))", new Object[] { Global.LDAP_ID, userName }, ctrls);

            //MetaDbHelper.note("NamingEnumeration retrieved");

            while (answer.hasMoreElements()) {
                SearchResult sr = answer.next();
                if (StringUtils.isEmpty(Global.LDAP_CONTEXT)) {
                    result = sr.getName();
                } else {
                    result = (sr.getName() + "," + Global.LDAP_CONTEXT);
                }

                //MetaDbHelper.note("Got DN: "+result);

                return result;
            }
        } catch (NamingException e) {
            MetaDbHelper.logEvent(e);
            //MetaDbHelper.note("LDAP Error: Failed Search");
        }
    } catch (NamingException e) {
        MetaDbHelper.logEvent(e);
        //MetaDbHelper.note("LDAP Error: Failed authentication");
    } finally {
        // Close the context when we're done
        try {
            if (ctx != null)
                ctx.close();
        } catch (NamingException e) {
        }
    }
    // No DN match found
    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 ava 2 s. com

    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:py.una.pol.karaku.util.LDAPUtil.java

/**
 * Recupera los usuarios de LDAP/*from  w w w .  j  av  a 2  s .c o  m*/
 * 
 * @return Una lista con los usuarios de LDAP
 */
public List<User> getUsers() {

    List<User> users = new ArrayList<User>();

    try {
        DirContext ctx = createInitialDirContext();

        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute("uid"));

        NamingEnumeration<SearchResult> answer = ctx.search("ou=users", matchAttrs);

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            String uid = sr.getName().substring(4);
            // No se retornan los usuarios especiales
            if (!uid.startsWith(LDAP_SPECIAL_USER_PREFIX) && !ListHelper.contains(EXCLUDED_USERS, uid)) {
                User user = new User();
                user.setUid(uid);
                Attributes atributos = sr.getAttributes();
                String cn = atributos.get("cn").toString().substring(4);
                user.setCn(cn);
                users.add(user);
            }
        }

    } catch (NamingException e) {
        throw new KarakuRuntimeException(e.getMessage(), e);
    }

    return users;

}

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

/**
 * Returns the CN (common name) for a given login name
 * //from  ww  w . java2s .c om
 * @param loginName
 *            the loginName of the user
 * @return CN as a String(if found), or null (else)
 */
private static String getCn(TSiteBean siteBean, String loginName) throws NamingException {
    String keyDn = null;
    DirContext ctx = getInitialContext(siteBean.getLdapServerURL(), siteBean.getLdapBindDN(),
            siteBean.getLdapBindPassword());
    if (ctx != null) {
        SearchControls ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        // Search for the user-id
        String searchStr = "(" + siteBean.getLdapAttributeLoginName() + "=" + loginName + ")";
        NamingEnumeration<SearchResult> answer = ctx.search("", searchStr, ctls);
        if (answer.hasMore()) {
            // retrieve the CN
            SearchResult sr = answer.next();
            keyDn = sr.getName();// + "," + ctx.getNameInNamespace();
            LOGGER.debug("Name = " + keyDn);
            String nameInNamespace = ctx.getNameInNamespace();
            LOGGER.debug("Name in namespace " + nameInNamespace);
            if (nameInNamespace != null && nameInNamespace.trim().length() > 0) {
                keyDn += "," + ctx.getNameInNamespace();
            }
            LOGGER.debug("entry found for LDAP-search >" + searchStr + "<: dn= >" + keyDn + "<!");
            answer.close(); // wo don't need more answers
        } else {
            LOGGER.debug("no entry found for LDAP-search >" + searchStr + "<!");
        }
        ctx.close();
    }
    return keyDn;
}

From source file:io.apiman.gateway.engine.policies.BasicAuthLDAPTest.java

@Test
@Ignore/*from  w  w  w  .j av  a2s . co  m*/
public void testLdap() throws Exception {
    DirContext ctx = createContext();
    Assert.assertNotNull(ctx);

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration<SearchResult> result = ctx.search("o=apiman", "(ObjectClass=*)", controls);

    System.out.println(" ==== Search Results ====");
    while (result.hasMore()) {
        SearchResult entry = result.next();
        System.out.println(" ===> " + entry.getName());
    }

}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

private boolean getUserInf(UserEdit edit, String filter) {

    String id = null;/*from w w w. j a  va  2  s  . c o m*/
    String firstName = null;
    String lastName = null;
    String employeenumber = null;
    String email = null;
    try {
        DirContext ctx = new InitialDirContext(env);

        // Setup subtree scope to tell LDAP to recursively descend directory structure
        // during searches.
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // We want the user's id, first name and last name ...
        searchControls.setReturningAttributes(new String[] { "uid", "givenName", "sn" });

        // Execute the search, starting at the directory level of Users
        NamingEnumeration results = ctx.search(getBasePath(), filter, searchControls);

        while (results.hasMore()) {
            SearchResult result = (SearchResult) results.next();
            String dn = result.getName().toString() + "," + getBasePath();
            Attributes attrs = ctx.getAttributes(dn);
            id = attrs.get("uid").get().toString();
            String cn = attrs.get("cn").get().toString();
            firstName = cn.substring(0, cn.indexOf(" "));
            lastName = cn.substring(cn.indexOf(" "));
            email = attrs.get("mail").get().toString();
        }

        results.close();
        ctx.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }

    edit.setId(id);
    edit.setFirstName(firstName);
    edit.setLastName(lastName);
    edit.setEmail(email);
    return true;
}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

public boolean authenticateUser(String userLogin, UserEdit edit, String password) {
    Hashtable env = new Hashtable();
    InitialDirContext ctx;/*  w ww  . ja  v a2s. co  m*/

    String INIT_CTX = "com.sun.jndi.ldap.LdapCtxFactory";
    String MY_HOST = getLdapHost() + ":" + getLdapPort();
    String cn;
    boolean returnVal = false;

    if (!password.equals("")) {

        env.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
        env.put(Context.PROVIDER_URL, MY_HOST);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_CREDENTIALS, "secret");

        String[] returnAttribute = { "ou" };
        SearchControls srchControls = new SearchControls();
        srchControls.setReturningAttributes(returnAttribute);
        srchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(userLogin) + "))";

        try {
            ctx = new InitialDirContext(env);
            NamingEnumeration answer = ctx.search(getBasePath(), searchFilter, srchControls);
            String trobat = "false";

            while (answer.hasMore() && trobat.equals("false")) {

                SearchResult sr = (SearchResult) answer.next();
                String dn = sr.getName().toString() + "," + getBasePath();

                // Second binding
                Hashtable authEnv = new Hashtable();
                try {
                    authEnv.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
                    authEnv.put(Context.PROVIDER_URL, MY_HOST);
                    authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
                    authEnv.put(Context.SECURITY_PRINCIPAL, sr.getName() + "," + getBasePath());
                    authEnv.put(Context.SECURITY_CREDENTIALS, password);
                    try {
                        DirContext authContext = new InitialDirContext(authEnv);
                        returnVal = true;
                        trobat = "true";
                        authContext.close();
                    } catch (AuthenticationException ae) {
                        M_log.info("Access forbidden");
                    }

                } catch (NamingException namEx) {
                    M_log.info("User doesn't exist");
                    returnVal = false;
                    namEx.printStackTrace();
                }
            }
            if (trobat.equals("false"))
                returnVal = false;

        } catch (NamingException namEx) {
            namEx.printStackTrace();
            returnVal = false;
        }
    }
    return returnVal;
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java

private String searchUser(String login, HashMap<String, String> userAttrs, DirContext ctx)
        throws NamingException {
    String uid;/*from ww w.jav a  2s  .  c  om*/
    SearchControls ctls = new SearchControls();
    ctls.setReturningObjFlag(true);
    ctls.setSearchScope(searchScope);
    String search = searchPattern.replaceAll(Pattern.quote("%LOGIN%"), escapeLDAPSearchFilter(login));
    log.debug("Searching LDAP for " + search);
    NamingEnumeration<SearchResult> answer = ctx.search(base, search, ctls);
    try {
        if (!answer.hasMore())
            throw new NoSuchElementException();
        log.debug("LDAP returned >=1 record.");
        SearchResult result = answer.next();
        uid = result.getName();
        for (Map.Entry<String, String> e : attributeMap.entrySet()) {
            log.debug("found LDAP attribute: " + e.getKey());
            Attribute a = result.getAttributes().get(e.getKey());
            if (a != null)
                userAttrs.put(e.getValue(), a.get().toString());
        }
    } finally {
        answer.close();
    }
    return uid;
}