Java Code Examples for org.springframework.ldap.query.SearchScope

The following examples show how to use org.springframework.ldap.query.SearchScope. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Gatekeeper   Source File: GatekeeperLdapLookupService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<GatekeeperSearchUserEntry> searchForUsers(String queryStr){
    logger.info("Searching for users matching "+queryStr);
    return ldapTemplate.search(
            LdapQueryBuilder.query()
                    .base(ldapProperties.getUsersBase())
                    .countLimit(10)
                    .searchScope(SearchScope.SUBTREE)
                    .where("objectClass")
                    .is(ldapObjectClass)
                    .and(LdapQueryBuilder.query()
                            .where(ldapUserId)
                            .like("*"+queryStr+"*")
                            .or(ldapUserName)
                            .like("*"+queryStr+"*")), getAttributesMapper());
}
 
Example 2
Source Project: spring-ldap   Source File: LdapTemplateParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(LdapTemplate.class);

    String contextSourceRef = getString(element, ATT_CONTEXT_SOURCE_REF, ContextSourceParser.DEFAULT_ID);
    builder.addPropertyReference("contextSource", contextSourceRef);
    builder.addPropertyValue("defaultCountLimit", getInt(element, ATT_COUNT_LIMIT, DEFAULT_COUNT_LIMIT));
    builder.addPropertyValue("defaultTimeLimit", getInt(element, ATT_TIME_LIMIT, DEFAULT_TIME_LIMIT));

    String searchScope = getString(element, ATT_SEARCH_SCOPE, SearchScope.SUBTREE.toString());
    builder.addPropertyValue("defaultSearchScope", SearchScope.valueOf(searchScope).getId());
    builder.addPropertyValue("ignorePartialResultException", getBoolean(element, ATT_IGNORE_PARTIAL_RESULT, false));
    builder.addPropertyValue("ignoreNameNotFoundException", getBoolean(element, ATT_IGNORE_NAME_NOT_FOUND, false));

    String odmRef = element.getAttribute(ATT_ODM_REF);
    if(StringUtils.hasText(odmRef)) {
        builder.addPropertyReference("objectDirectoryMapper", odmRef);
    }

    String id = getString(element, AbstractBeanDefinitionParser.ID_ATTRIBUTE, DEFAULT_ID);

    BeanDefinition beanDefinition = builder.getBeanDefinition();
    parserContext.registerBeanComponent(new BeanComponentDefinition(beanDefinition, id));

    return beanDefinition;
}
 
Example 3
private String accountAsUserDn2Authentication(String loginName, LdapE ldap, LdapContextSource contextSource, AndFilter filter) {
    contextSource.setUserDn(ldap.getAccount());
    contextSource.setPassword(ldap.getPassword());
    contextSource.afterPropertiesSet();
    LdapTemplate template = new LdapTemplate(contextSource);
    if (DirectoryType.MICROSOFT_ACTIVE_DIRECTORY.value().equals(ldap.getDirectoryType())) {
        template.setIgnorePartialResultException(true);
    }
    String userDn = null;
    try {
        List<String> names =
                template.search(
                        query()
                                .searchScope(SearchScope.SUBTREE)
                                .filter(filter),
                        new AbstractContextMapper() {
                            @Override
                            protected Object doMapFromContext(DirContextOperations ctx) {
                                return ctx.getNameInNamespace();
                            }
                        });
        userDn = getUserDn(names, ldap.getLoginNameField(), loginName);
    } catch (Exception e) {
        LOG.error("use ldap account as userDn and password to authentication but search failed, filter {}," +
                " maybe the account or password is illegal, and check for the ldap config, exception {}", filter, e);
    }
    return userDn;
}
 
Example 4
@Override
protected Set<String> loadUserMemberships(String userName){
    {
        Optional<GatekeeperUserEntry> user = userCache.getUnchecked(userName);
        String userDn = user.get().getDn();

        LdapQuery memberOfApplication = LdapQueryBuilder.query()
                .base(ldapUserGroupsBase)
                .searchScope(SearchScope.SUBTREE)
                .attributes(ldapUserCn, ldapUserDn)
                .filter("(member:" + LDAP_MATCHING_RULE_IN_CHAIN + ":=" + userDn + ")");

        return new HashSet<>(ldapTemplate.search(memberOfApplication, getStringAttributesMapper(ldapUserCn)));
    }
}
 
Example 5
protected GatekeeperUserEntry loadUser(String userName){
    logger.info("Loading info for " + userName);
    LdapQuery query = LdapQueryBuilder.query()
            .base(ldapProperties.getUsersBase()).countLimit(1)
            .searchScope(SearchScope.SUBTREE)
            .attributes(ldapUserId, ldapUserDn, ldapUserEmail, ldapUserName)
            .where("objectClass")
            .is(ldapObjectClass)
            .and(ldapUserId)
            .is(userName);
    List<GatekeeperUserEntry> subjects = ldapTemplate.search(query, getAttributesMapper());

    if (subjects != null && subjects.size() > 0) {
        return subjects.get(0);
        //check to see if account is test account (only if testUsersBase is provided)
    } else if(ldapProperties.getTestUsersBase() != null) {
        query = LdapQueryBuilder.query()
                .base(ldapProperties.getTestUsersBase()).countLimit(1)
                .searchScope(SearchScope.SUBTREE)
                .attributes(ldapUserId, ldapUserDn, ldapUserEmail, ldapUserName)
                .where("objectCategory")
                .is(ldapObjectClass)
                .and(ldapUserId)
                .is(userName);
        subjects = ldapTemplate.search(query, getAttributesMapper());
        //return null;
        if (subjects != null && subjects.size() > 0) {
            return subjects.get(0);
        }
    }
    return null;
}
 
Example 6
Source Project: apollo   Source File: LdapUserService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 查询条件
 */
private ContainerCriteria ldapQueryCriteria() {
  ContainerCriteria criteria = query()
      .searchScope(SearchScope.SUBTREE)
      .where("objectClass").is(objectClassAttrName);
  if (memberOf.length > 0 && !StringUtils.isEmpty(memberOf[0])) {
    ContainerCriteria memberOfFilters = query().where(MEMBER_OF_ATTR_NAME).is(memberOf[0]);
    Arrays.stream(memberOf).skip(1)
        .forEach(filter -> memberOfFilters.or(MEMBER_OF_ATTR_NAME).is(filter));
    criteria.and(memberOfFilters);
  }
  return criteria;
}
 
Example 7
@Override
public Collection<User> search(String query) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        String usersSearchFilter = environment.getProperty("lookup.user.filter", LDAP_DEFAULT_LOOKUP_FILTER);
        String hardcodedFilter = usersSearchFilter.replaceAll("\\{0}", LdapUtils.addWhitespaceWildcards(query));

        LdapQuery ldapQuery = LdapQueryBuilder
                .query()
                .base(baseDn)
                .countLimit(20)
                .timeLimit(5000)
                .searchScope(SearchScope.SUBTREE)
                .attributes(
                        LDAP_ATTRIBUTE_GIVENNAME,
                        LDAP_ATTRIBUTE_SURNAME,
                        LDAP_ATTRIBUTE_MAIL,
                        LDAP_ATTRIBUTE_DISPLAYNAME)
                .filter(new HardcodedFilter(hardcodedFilter));

        return ldapTemplate.search(ldapQuery, USER_CONTEXT_MAPPER);
    } catch(LimitExceededException lee) {
        LOGGER.info("Too much results while searching for [{}]. Returns an empty list.", query);
        return Collections.emptyList();
    } catch(CommunicationException ce) {
        LOGGER.error("LDAP server is not reachable.");
        return Collections.emptyList();
    } finally {
        Thread.currentThread().setContextClassLoader(classLoader);
    }
}
 
Example 8
Source Project: spring-ldap   Source File: LdapTemplateSearchResultITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSearch_LdapQuery_AttributesMapper_SearchScope() {
    attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES);
    attributesMapper.setExpectedValues(ALL_VALUES);

    List<Object> list = tested.search(query()
            .base(BASE_STRING)
            .searchScope(SearchScope.ONELEVEL)
            .where("objectclass").is("person").and("sn").is("Person2"),
            attributesMapper);
    assertThat(list).isEmpty();
}
 
Example 9
Source Project: spring-ldap   Source File: LdapTemplateSearchResultITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSearch_LdapQuery_AttributesMapper_SearchScope_CorrectBase() {
    attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES);
    attributesMapper.setExpectedValues(ALL_VALUES);

    List<Object> list = tested.search(query()
            .base("ou=company1,ou=Sweden")
            .searchScope(SearchScope.ONELEVEL)
            .where("objectclass").is("person").and("sn").is("Person2"),
            attributesMapper);
    assertThat(list).hasSize(1);
}
 
Example 10
Source Project: spring-ldap   Source File: LdapTemplateSearchResultITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSearch_ContextMapper_LdapQuery_SearchScope() {
    contextMapper.setExpectedAttributes(ALL_ATTRIBUTES);
    contextMapper.setExpectedValues(ALL_VALUES);
    List<DirContextAdapter> list = tested.search(query()
            .base(BASE_NAME)
            .searchScope(SearchScope.ONELEVEL)
            .where("objectclass").is("person").and("sn").is("Person2"),
            contextMapper);
    assertThat(list).isEmpty();
}
 
Example 11
Source Project: spring-ldap   Source File: LdapTemplateSearchResultITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSearch_ContextMapper_LdapQuery_SearchScope_CorrectBase() {
    contextMapper.setExpectedAttributes(ALL_ATTRIBUTES);
    contextMapper.setExpectedValues(ALL_VALUES);
    List<DirContextAdapter> list = tested.search(query()
            .base("ou=company1,ou=Sweden")
            .searchScope(SearchScope.ONELEVEL)
            .where("objectclass").is("person").and("sn").is("Person2"),
            contextMapper);
    assertThat(list).hasSize(1);
}
 
Example 12
Source Project: spring-ldap   Source File: LdapTemplateSearchResultITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSearchForContext_LdapQuery_SearchScope_CorrectBase() {
    DirContextOperations result =
            tested.searchForContext(query()
            .searchScope(SearchScope.ONELEVEL)
            .base("ou=company1,ou=Sweden")
            .where("objectclass").is("person").and("sn").is("Person2"));

    assertThat(result).isNotNull();
    assertThat(result.getStringAttribute("sn")).isEqualTo("Person2");
}
 
Example 13
@Test
public void testSearch_LdapQuery_AttributesMapper_SearchScope() {
    attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES);
    attributesMapper.setExpectedValues(ALL_VALUES);

    List<Object> list = tested.search(query()
            .base(BASE_STRING)
            .searchScope(SearchScope.ONELEVEL)
            .where("objectclass").is("person").and("sn").is("Person2"),
            attributesMapper);
    assertThat(list).isEmpty();
}
 
Example 14
@Test
public void testSearch_LdapQuery_AttributesMapper_SearchScope_CorrectBase() {
    attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES);
    attributesMapper.setExpectedValues(ALL_VALUES);

    List<Object> list = tested.search(query()
            .base("ou=company1,ou=Sweden")
            .searchScope(SearchScope.ONELEVEL)
            .where("objectclass").is("person").and("sn").is("Person2"),
            attributesMapper);
    assertThat(list).hasSize(1);
}
 
Example 15
@Test
public void testSearch_ContextMapper_LdapQuery_SearchScope() {
    contextMapper.setExpectedAttributes(ALL_ATTRIBUTES);
    contextMapper.setExpectedValues(ALL_VALUES);
    List<DirContextAdapter> list = tested.search(query()
            .base(BASE_NAME)
            .searchScope(SearchScope.ONELEVEL)
            .where("objectclass").is("person").and("sn").is("Person2"),
            contextMapper);
    assertThat(list).isEmpty();
}
 
Example 16
@Test
public void testSearch_ContextMapper_LdapQuery_SearchScope_CorrectBase() {
    contextMapper.setExpectedAttributes(ALL_ATTRIBUTES);
    contextMapper.setExpectedValues(ALL_VALUES);
    List<DirContextAdapter> list = tested.search(query()
            .base("ou=company1,ou=Sweden")
            .searchScope(SearchScope.ONELEVEL)
            .where("objectclass").is("person").and("sn").is("Person2"),
            contextMapper);
    assertThat(list).hasSize(1);
}
 
Example 17
@Test
public void testSearchForContext_LdapQuery_SearchScope_CorrectBase() {
    DirContextOperations result =
            tested.searchForContext(query()
            .searchScope(SearchScope.ONELEVEL)
            .base("ou=company1,ou=Sweden")
            .where("objectclass").is("person").and("sn").is("Person2"));

    assertThat(result).isNotNull();
    assertThat(result.getStringAttribute("sn")).isEqualTo("Person2");
}
 
Example 18
private boolean ldapAuthentication(Long organizationId, String loginName, String credentials) {
    LdapE ldap = ldapService.queryByOrgId(organizationId);
    if (ldap != null && ldap.getEnabled()) {
        LdapContextSource contextSource = new LdapContextSource();
        String url = ldap.getServerAddress() + ":" + ldap.getPort();
        int connectionTimeout = ldap.getConnectionTimeout();
        contextSource.setUrl(url);
        contextSource.setBase(ldap.getBaseDn());
        setConnectionTimeout(contextSource, connectionTimeout);
        contextSource.afterPropertiesSet();

        LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
        //ad目录不设置会报错
        if (DirectoryType.MICROSOFT_ACTIVE_DIRECTORY.value().equals(ldap.getDirectoryType())) {
            ldapTemplate.setIgnorePartialResultException(true);
        }
        String userDn = null;
        boolean anonymousFetchFailed = false;

        AndFilter filter = getLoginFilter(ldap, loginName);
        try {
            List<String> names =
                    ldapTemplate.search(
                            query()
                                    .searchScope(SearchScope.SUBTREE)
                                    .filter(filter),
                            new AbstractContextMapper() {
                                @Override
                                protected Object doMapFromContext(DirContextOperations ctx) {
                                    return ctx.getNameInNamespace();
                                }
                            });
            userDn = getUserDn(names, ldap.getLoginNameField(), loginName);
        } catch (Exception e) {
            anonymousFetchFailed = true;
            LOG.error("ldap anonymous search failed, filter {}, exception {}", filter, e);
        }
        if (anonymousFetchFailed) {
            userDn = accountAsUserDn2Authentication(loginName, ldap, contextSource, filter);
        }
        if (userDn == null) {
            LOG.error("can not get userDn by filter {}, login failed", filter);
            return false;
        }
        return authentication(credentials, contextSource, userDn);
    } else {
        throw new AuthenticationServiceException(LoginException.LDAP_IS_DISABLE.value());
    }
}
 
Example 19
protected Set<String> loadUserMemberships(String userName){
    Pattern cnPattern = Pattern.compile("cn=([- _A-Za-z0-9]+)", Pattern.CASE_INSENSITIVE);

    logger.info("Checking Memberships for " +userName );
    Set<String> memberships = new HashSet<>();
    String memberof = "memberOf";
    LdapQuery query = LdapQueryBuilder.query()
            .base(ldapProperties.getUsersBase()).countLimit(1000)
            .searchScope(SearchScope.SUBTREE)
            .attributes(memberof)
            .where("objectClass")
            .is(ldapObjectClass)
            .and(ldapUserId)
            .is(userName);


    LinkedList<String[]> subjects = (LinkedList<String[]>)ldapTemplate.search(query, new OpenLdapMembershipsMapper());

    if (subjects == null || subjects.size() == 0) {
        if(ldapProperties.getTestUsersBase() != null) {
            query = LdapQueryBuilder.query()
                    .base(ldapProperties.getTestUsersBase()).countLimit(1000)
                    .searchScope(SearchScope.SUBTREE)
                    .attributes("memberOf")
                    .where("objectClass")
                    .is(ldapObjectClass)
                    .and(ldapUserId)
                    .is(userName);
            subjects = (LinkedList<String[]>) ldapTemplate.search(query, new OpenLdapMembershipsMapper());
        }
    }

    HashSet<String> extracted = new HashSet<>();

    Arrays.asList(subjects.getFirst()).forEach(item -> {
        Matcher m = cnPattern.matcher(item);
        if(m.find()) {
            extracted.add(m.group(1));
        }
    });

    return extracted;
}
 
Example 20
Source Project: spring-ldap   Source File: LdapTemplateSearchResultITest.java    License: Apache License 2.0 4 votes vote down vote up
@Test(expected = EmptyResultDataAccessException.class)
public void testSearchForContext_LdapQuery_SearchScopeNotFound() {
    tested.searchForContext(query()
            .searchScope(SearchScope.ONELEVEL)
            .where("objectclass").is("person").and("sn").is("Person2"));
}
 
Example 21
@Test(expected = EmptyResultDataAccessException.class)
public void testSearchForContext_LdapQuery_SearchScopeNotFound() {
    tested.searchForContext(query()
            .searchScope(SearchScope.ONELEVEL)
            .where("objectclass").is("person").and("sn").is("Person2"));
}