org.springframework.ldap.query.SearchScope Java Examples

The following examples show how to use org.springframework.ldap.query.SearchScope. 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 File: LdapTemplateParser.java    From spring-ldap with 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 #2
Source File: GatekeeperLdapLookupService.java    From Gatekeeper with 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 #3
Source File: LdapTemplateSearchResultITest.java    From spring-ldap with 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 #4
Source File: LdapTemplateSearchResultNamespaceConfigITest.java    From spring-ldap with 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 #5
Source File: LdapTemplateSearchResultNamespaceConfigITest.java    From spring-ldap with 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 #6
Source File: LdapTemplateSearchResultNamespaceConfigITest.java    From spring-ldap with 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 #7
Source File: LdapTemplateSearchResultNamespaceConfigITest.java    From spring-ldap with 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 #8
Source File: LdapTemplateSearchResultNamespaceConfigITest.java    From spring-ldap with 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 File: LdapTemplateSearchResultITest.java    From spring-ldap with 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 #10
Source File: LdapTemplateSearchResultITest.java    From spring-ldap with 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 #11
Source File: LdapTemplateSearchResultITest.java    From spring-ldap with 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 #12
Source File: LdapTemplateSearchResultITest.java    From spring-ldap with 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 #13
Source File: LdapIdentityLookup.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@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 #14
Source File: LdapUserService.java    From apollo with 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 #15
Source File: GatekeeperOpenLDAPAuthorizationService.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
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 #16
Source File: GatekeeperActiveDirectoryLDAPAuthorizationService.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
@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 #17
Source File: ChoerodonAuthenticationProvider.java    From oauth-server with Apache License 2.0 5 votes vote down vote up
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 #18
Source File: ChoerodonAuthenticationProvider.java    From oauth-server with Apache License 2.0 4 votes vote down vote up
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
Source File: LdapTemplateSearchResultITest.java    From spring-ldap with 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 #20
Source File: GatekeeperOpenLDAPAuthorizationService.java    From Gatekeeper with Apache License 2.0 4 votes vote down vote up
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 #21
Source File: LdapTemplateSearchResultNamespaceConfigITest.java    From spring-ldap with 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"));
}