Example usage for javax.naming.directory SearchControls SUBTREE_SCOPE

List of usage examples for javax.naming.directory SearchControls SUBTREE_SCOPE

Introduction

In this page you can find the example usage for javax.naming.directory SearchControls SUBTREE_SCOPE.

Prototype

int SUBTREE_SCOPE

To view the source code for javax.naming.directory SearchControls SUBTREE_SCOPE.

Click Source Link

Document

Search the entire subtree rooted at the named object.

Usage

From source file:org.rhq.enterprise.server.core.jaas.LdapLoginModule.java

/**
 * A simple method to construct a SearchControls object for use when doing LDAP searches. All of the defaults are
 * used, with the exception of the scope, which is set to SUBTREE rather than the default of ONE_LEVEL
 *
 * @return controls what is searched in LDAP
 *//*from w  w w .  j  a v  a 2s  . c  o  m*/
private SearchControls getSearchControls() {
    // Set the scope to subtree, default is one-level
    int scope = SearchControls.SUBTREE_SCOPE;

    // No limit on the time waiting for a response
    int timeLimit = 0;

    // No limit on the number of entries returned
    long countLimit = 0;

    // Attributes to return.
    String[] returnedAttributes = null;

    // Don't return the object
    boolean returnObject = false;

    // No dereferencing during the search
    boolean deference = false;

    SearchControls constraints = new SearchControls(scope, countLimit, timeLimit, returnedAttributes,
            returnObject, deference);
    return constraints;
}

From source file:org.apache.zeppelin.server.ActiveDirectoryGroupRealm.java

private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set<String> roleNames = new LinkedHashSet<>();

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String userPrincipalName = username;
    if (principalSuffix != null) {
        userPrincipalName += principalSuffix;
    }/*from w  ww  .  jav a2s  .co  m*/

    String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";
    Object[] searchArguments = new Object[] { userPrincipalName };

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);

    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        if (log.isDebugEnabled()) {
            log.debug("Retrieving group 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().equals("memberOf")) {

                    Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);

                    if (log.isDebugEnabled()) {
                        log.debug("Groups found for user [" + username + "]: " + groupNames);
                    }

                    Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
                    roleNames.addAll(rolesForGroups);
                }
            }
        }
    }
    return roleNames;
}

From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java

private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set<String> roleNames = new LinkedHashSet<>();

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String userPrincipalName = username;
    if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) {
        userPrincipalName += principalSuffix;
    }//from   ww w .  j ava2s .c  om

    String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";
    Object[] searchArguments = new Object[] { userPrincipalName };

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);

    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        if (log.isDebugEnabled()) {
            log.debug("Retrieving group 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().equals("memberOf")) {

                    Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);

                    if (log.isDebugEnabled()) {
                        log.debug("Groups found for user [" + username + "]: " + groupNames);
                    }

                    Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
                    roleNames.addAll(rolesForGroups);
                }
            }
        }
    }
    return roleNames;
}

From source file:ru.efo.security.ADUserDetailsService.java

private ADUserDetails loadUserByUsername(DirContext context, String username, String password)
        throws UsernameNotFoundException {
    try {//www .  j a  v  a 2  s  . c  om
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // search for username
        NamingEnumeration<SearchResult> renum = context.search(userSearchBase,
                "(&(objectClass=user)(sAMAccountName={0}))", new Object[] { username }, controls);
        if (!renum.hasMoreElements()) {
            throw new UsernameNotFoundException("User '" + username + "' is not exist");
        }
        SearchResult result = renum.next();
        final Attributes attributes = result.getAttributes();

        // User's display name
        String displayName = null;
        Attribute attr = attributes.get(displayNameAttribute);
        if (attr != null) {
            displayName = attr.get().toString();
        }
        if (!StringUtils.hasText(displayName))
            displayName = username;
        logger.log(Level.FINE, "Display name: " + displayName);

        // User's email
        String email = null;
        attr = attributes.get(emailAttribute);
        if (attr != null) {
            email = attr.get().toString();
        }
        logger.log(Level.FINE, "E-mail: " + email);

        // User's phone number
        String phone = null;
        attr = attributes.get(phoneAttribute);
        if (attr != null) {
            phone = attr.get().toString();
        }
        logger.log(Level.FINE, "Phone: " + phone);

        // Is user blocked
        boolean blocked = false;
        attr = attributes.get("userAccountControl");
        if (attr != null) {
            blocked = (Long.parseLong(attr.get().toString()) & 2) != 0;
        }
        logger.log(Level.FINE, "Blocked: " + blocked);

        // describe roles and groups
        final Set<String> roles = new TreeSet<>();
        final Set<String> groups = new TreeSet<>();
        Attribute memberOf = attributes.get("memberOf");
        describeRoles(context, memberOf, groups, roles);

        // Describe user primary role
        Attribute attrPrimaryGroupId = attributes.get("primaryGroupId");
        Attribute attrObjectSid = attributes.get("objectSid");
        if (attrPrimaryGroupId != null && attrObjectSid != null) {
            int primaryGroupId = Integer.parseInt(attrPrimaryGroupId.get().toString());
            byte[] objectSid = (byte[]) attrObjectSid.get();
            // add primary group RID
            for (int i = 0; i < 4; i++) {
                objectSid[objectSid.length - 4 + i] = (byte) (primaryGroupId & 0xFF);
                primaryGroupId >>= 8;
            }
            StringBuilder tmp = new StringBuilder();
            for (int i = 2; i <= 7; i++) {
                tmp.append(Integer.toHexString(objectSid[i] & 0xFF));
            }
            // convert objectSid to String
            StringBuilder sidBuilder = new StringBuilder("S-").append(objectSid[0]).append("-")
                    .append(Long.parseLong(tmp.toString(), 16));
            // the sub authorities count
            int count = objectSid[1];
            // add authorities
            for (int i = 0; i < count; i++) {
                tmp.setLength(0);

                int offset = i * 4;
                tmp.append(String.format("%02X%02X%02X%02X", (objectSid[11 + offset] & 0xFF),
                        (objectSid[10 + offset] & 0xFF), (objectSid[9 + offset] & 0xFF),
                        (objectSid[8 + offset] & 0xFF)));
                sidBuilder.append('-').append(Long.parseLong(tmp.toString(), 16));
            }
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            renum = context.search(userSearchBase, "(&(objectClass=group)(objectSid={0}))",
                    new Object[] { sidBuilder.toString() }, searchControls);
            if (renum.hasMoreElements()) {
                result = renum.next();
                attr = result.getAttributes().get("distinguishedName");
                describeRoles(context, attr, groups, roles);
            }
        }
        return new ADUserDetails(username, password, displayName, email, phone, blocked, groups, roles);
    } catch (NamingException ex) {
        logger.log(Level.SEVERE, "Could not find user '" + username + "'", ex);
        throw new UsernameNotFoundException(ex.getMessage());
    }
}

From source file:org.apache.directory.studio.connection.core.io.jndi.LdifSearchLogger.java

/**
 * {@inheritDoc}//from   ww w.j a v  a2 s  . co  m
 */
public void logSearchRequest(Connection connection, String searchBase, String filter,
        SearchControls searchControls, AliasDereferencingMethod aliasesDereferencingMethod, Control[] controls,
        long requestNum, NamingException ex) {
    if (!isSearchRequestLogEnabled()) {
        return;
    }

    String scopeAsString = searchControls.getSearchScope() == SearchControls.SUBTREE_SCOPE ? "wholeSubtree (2)" //$NON-NLS-1$
            : searchControls.getSearchScope() == SearchControls.ONELEVEL_SCOPE ? "singleLevel (1)" //$NON-NLS-1$
                    : "baseObject (0)"; //$NON-NLS-1$
    String attributesAsString = searchControls.getReturningAttributes() == null ? "*" //$NON-NLS-1$
            : searchControls.getReturningAttributes().length == 0 ? "1.1" //$NON-NLS-1$
                            : StringUtils.join(searchControls.getReturningAttributes(), " ");
    String aliasAsString = aliasesDereferencingMethod == AliasDereferencingMethod.ALWAYS ? "derefAlways (3)" //$NON-NLS-1$
            : aliasesDereferencingMethod == AliasDereferencingMethod.FINDING ? "derefFindingBaseObj (2)" //$NON-NLS-1$
                    : aliasesDereferencingMethod == AliasDereferencingMethod.SEARCH ? "derefInSearching (1)" //$NON-NLS-1$
                            : "neverDerefAliases (0)"; //$NON-NLS-1$

    // build LDAP URL
    LdapUrl url = Utils.getLdapURL(connection, searchBase, searchControls.getSearchScope(), filter,
            searchControls.getReturningAttributes());

    // build command line
    String cmdLine = Utils.getLdapSearchCommandLine(connection, searchBase, searchControls.getSearchScope(),
            aliasesDereferencingMethod, searchControls.getCountLimit(), searchControls.getTimeLimit(), filter,
            searchControls.getReturningAttributes());

    // build 
    Collection<LdifLineBase> lines = new ArrayList<LdifLineBase>();
    lines.add(LdifCommentLine.create("# LDAP URL     : " + url.toString())); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# command line : " + cmdLine.toString())); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# baseObject   : " + searchBase)); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# scope        : " + scopeAsString)); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# derefAliases : " + aliasAsString)); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# sizeLimit    : " + searchControls.getCountLimit())); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# timeLimit    : " + searchControls.getTimeLimit())); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# typesOnly    : " + "False")); //$NON-NLS-1$ //$NON-NLS-2$
    lines.add(LdifCommentLine.create("# filter       : " + filter)); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# attributes   : " + attributesAsString)); //$NON-NLS-1$
    if (controls != null) {
        for (Control control : controls) {
            lines.add(LdifCommentLine.create("# control      : " + control.getID())); //$NON-NLS-1$
        }
    }
    lines.add(LdifSepLine.create());

    String formattedString = ""; //$NON-NLS-1$
    for (LdifLineBase line : lines) {
        formattedString += line.toFormattedString(LdifFormatParameters.DEFAULT);
    }

    log(formattedString, "SEARCH REQUEST (" + requestNum + ")", ex, connection); //$NON-NLS-1$ //$NON-NLS-2$
}

From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java

/**
 * Gathers attributes from JNDI storage to the supplied attributes object.
 * @see com.alfaariss.oa.engine.core.attribute.gather.processor.IProcessor#process(java.lang.String, com.alfaariss.oa.api.attribute.IAttributes)
 *//*from w ww. j a va 2  s  .  c  o m*/
public void process(String sUserId, IAttributes oAttributes) throws AttributeException {
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (_listGather.size() > 0) {
            String[] saAttributes = _listGather.toArray(new String[0]);
            oScope.setReturningAttributes(saAttributes);
        }

        String searchFilter = resolveSearchQuery(sUserId);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attributes for id: ");
            sbFailed.append(sUserId);
            _logger.error(sbFailed.toString(), e);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.debug("User unknown: " + sUserId);
            return;
        }

        if (oNamingEnumeration.hasMore()) {
            SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
            Attributes oSearchedAttributes = oSearchResult.getAttributes();
            NamingEnumeration neAttributes = oSearchedAttributes.getAll();
            while (neAttributes.hasMore()) {
                Attribute oAttribute = (Attribute) neAttributes.next();
                String sAttributeName = oAttribute.getID();
                String sMappedName = _htMapper.get(sAttributeName);
                if (sMappedName != null)
                    sAttributeName = sMappedName;

                if (oAttribute.size() > 1) {
                    Vector<Object> vValue = new Vector<Object>();
                    NamingEnumeration neAttribute = oAttribute.getAll();
                    while (neAttribute.hasMore())
                        vValue.add(neAttribute.next());

                    oAttributes.put(sAttributeName, vValue);
                } else {
                    Object oValue = oAttribute.get();
                    if (oValue == null)
                        oValue = "";
                    oAttributes.put(sAttributeName, oValue);
                }
            }
        }
    } catch (AttributeException e) {
        throw e;
    } catch (NamingException e) {
        _logger.debug("Failed to fetch attributes for user: " + sUserId, e);
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields for user with id: " + sUserId, e);
        throw new AttributeException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + sUserId,
                        e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + sUserId, e);
            }
        }
    }
}

From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java

/**
 *
 *//*  w ww.ja  va2 s .  c  o m*/
public void doUpdateCredential(String userName, Object newCredential, Object oldCredential)
        throws UserStoreException {

    if (!isSSLConnection) {
        logger.warn("Unsecured connection is being used. Password operations will fail");
    }

    DirContext dirContext = this.connectionSource.getContext();
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userListFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER);
    String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
    // String searchFilter =
    // realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    String searchFilter = "(&" + userListFilter + "(" + userNameAttribute + "="
            + escapeSpecialCharactersForFilter(userName) + "))";

    SearchControls searchControl = new SearchControls();
    String[] returningAttributes = { "CN" };
    searchControl.setReturningAttributes(returningAttributes);
    searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    DirContext subDirContext = null;
    NamingEnumeration<SearchResult> searchResults = null;
    try {
        // search the user with UserNameAttribute and obtain its CN attribute
        searchResults = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControl);
        SearchResult user = null;
        int count = 0;
        while (searchResults.hasMore()) {
            if (count > 0) {
                throw new UserStoreException(
                        "There are more than one result in the user store " + "for user: " + userName);
            }
            user = searchResults.next();
            count++;
        }
        String userCNValue = null;
        if (user.getAttributes() != null) {
            Attribute cnAttribute = user.getAttributes().get("CN");
            if (cnAttribute != null) {
                userCNValue = (String) cnAttribute.get();
            } else {
                throw new UserStoreException("Can not update credential: CN attribute is null");
            }
        }

        ModificationItem[] mods = null;

        // The user tries to change his own password
        if (oldCredential != null && newCredential != null) {
            mods = new ModificationItem[1];
            /*
            * byte[] oldUnicodePassword = createUnicodePassword((String) oldCredential); byte[]
            * newUnicodePassword = createUnicodePassword((String) newCredential);
            */
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE,
                            createUnicodePassword((String) newCredential)));
            /*
             * mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(
             * LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, newUnicodePassword));
             */
        }
        subDirContext = (DirContext) dirContext.lookup(searchBase);
        subDirContext.modifyAttributes("CN" + "=" + escapeSpecialCharactersForDN(userCNValue), mods);

    } catch (NamingException e) {
        String error = "Can not access the directory service for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(error, e);
        }
        throw new UserStoreException(error, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(searchResults);
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }

}

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 ww.  j  a va  2  s .  c o  m*/

    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:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

protected boolean authenticate(String username) throws Exception {
    DirContext context = open();/*from w  ww  . j a  v  a  2  s  .  c  om*/
    try {

        String filter = userSearchMatchingFormat.format(new String[] { username });
        SearchControls constraints = new SearchControls();
        if (userSearchSubtreeBool) {
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }

        // setup attributes
        String[] attribs;
        if (userRoleName == null) {
            attribs = new String[] {};
        } else {
            attribs = new String[] { userRoleName };
        }
        constraints.setReturningAttributes(attribs);

        NamingEnumeration results = context.search(userBase, filter, constraints);

        if (results == null || !results.hasMore()) {
            log.error("No roles associated with user " + username);
            loginSucceeded = false;
            throw new FailedLoginException();
        }

        SearchResult result = (SearchResult) results.next();

        if (results.hasMore()) {
            // ignore for now
        }
        NameParser parser = context.getNameParser("");
        Name contextName = parser.parse(context.getNameInNamespace());
        Name baseName = parser.parse(userBase);
        Name entryName = parser.parse(result.getName());
        Name name = contextName.addAll(baseName);
        name = name.addAll(entryName);
        String dn = name.toString();

        Attributes attrs = result.getAttributes();
        if (attrs == null) {
            return false;
        }
        ArrayList<String> roles = null;
        if (userRoleName != null) {
            roles = addAttributeValues(userRoleName, attrs, roles);
        }
        // check the credentials by binding to server
        // bindUser(context, dn);
        // if authenticated add more roles
        roles = getRoles(context, dn, username, roles);
        for (String role : roles) {
            groups.add(role);
        }
        if (groups.isEmpty()) {
            log.error("No roles associated with user " + username);
            loginSucceeded = false;
            throw new FailedLoginException();
        } else
            loginSucceeded = true;

    } catch (CommunicationException e) {
        close(context);
        throw (LoginException) new FailedLoginException().initCause(e);
    } catch (NamingException e) {
        close(context);
        throw (LoginException) new FailedLoginException().initCause(e);
    }
    return true;
}

From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public List<String> getGroups(String username, DirContext context) throws MappingException {

    List<String> userGroups = new ArrayList<String>();

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {/*  ww  w  . jav  a  2 s . c  o m*/

        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String groupEntry = null;
        try {
            //try to look the user up
            User user = userManager.findUser(username);
            if (user instanceof LdapUser) {
                LdapUser ldapUser = LdapUser.class.cast(user);
                Attribute dnAttribute = ldapUser.getOriginalAttributes().get(getLdapDnAttribute());
                if (dnAttribute != null) {
                    groupEntry = String.class.cast(dnAttribute.get());
                }

            }
        } catch (UserNotFoundException e) {
            log.warn("Failed to look up user {}. Computing distinguished name manually", username, e);
        } catch (UserManagerException e) {
            log.warn("Failed to look up user {}. Computing distinguished name manually", username, e);
        }
        if (groupEntry == null) {
            //failed to look up the user's groupEntry directly
            StringBuilder builder = new StringBuilder();
            String posixGroup = "posixGroup";
            if (posixGroup.equals(getLdapGroupClass())) {
                builder.append(username);
            } else {
                builder.append(this.userIdAttribute).append("=").append(username).append(",")
                        .append(getBaseDn());
            }
            groupEntry = builder.toString();
        }

        String filter = new StringBuilder().append("(&").append("(objectClass=" + getLdapGroupClass() + ")")
                .append("(").append(getLdapGroupMember()).append("=").append(Rdn.escapeValue(groupEntry))
                .append(")").append(")").toString();

        log.debug("filter: {}", filter);

        namingEnumeration = context.search(getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();

            List<String> allMembers = new ArrayList<String>();

            Attribute uniqueMemberAttr = searchResult.getAttributes().get(getLdapGroupMember());

            if (uniqueMemberAttr != null) {
                NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr
                        .getAll();
                while (allMembersEnum.hasMore()) {

                    String userName = allMembersEnum.next();
                    //the original dn
                    allMembers.add(userName);
                    // uid=blabla we only want bla bla
                    userName = StringUtils.substringAfter(userName, "=");
                    userName = StringUtils.substringBefore(userName, ",");
                    allMembers.add(userName);
                }
                close(allMembersEnum);
            }

            if (allMembers.contains(username)) {
                String groupName = searchResult.getName();
                // cn=blabla we only want bla bla
                groupName = StringUtils.substringAfter(groupName, "=");
                userGroups.add(groupName);

            } else if (allMembers.contains(groupEntry)) {
                String groupName = searchResult.getName();
                // cn=blabla we only want bla bla
                groupName = StringUtils.substringAfter(groupName, "=");
                userGroups.add(groupName);
            }

        }

        return userGroups;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    } finally {
        close(namingEnumeration);
    }
}