Java Code Examples for org.springframework.ldap.core.LdapTemplate#search()

The following examples show how to use org.springframework.ldap.core.LdapTemplate#search() . 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: SpringLdap.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void queryVulnerableToInjection(LdapTemplate template, String jndiInjectMe, SearchControls searchControls, DirContextProcessor dirContextProcessor) throws NamingException {
    template.list(jndiInjectMe);
    template.list(jndiInjectMe, new DefaultNameClassPairMapper());
    template.list(jndiInjectMe, new CountNameClassPairCallbackHandler());

    template.lookup(jndiInjectMe);
    template.lookup(jndiInjectMe, new DefaultIncrementalAttributesMapper());
    template.lookup(jndiInjectMe, new LdapEntryIdentificationContextMapper());

    template.search(jndiInjectMe,"dn=1",searchControls,new CountNameClassPairCallbackHandler());
    template.search(jndiInjectMe,"dn=1",searchControls,new DefaultIncrementalAttributesMapper(), dirContextProcessor);
    template.search(jndiInjectMe,"dn=1",searchControls,new LdapEntryIdentificationContextMapper(),dirContextProcessor);
    template.search(jndiInjectMe,"dn=1",searchControls,new CountNameClassPairCallbackHandler(),dirContextProcessor);
    template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,true,new CountNameClassPairCallbackHandler());
    template.search(jndiInjectMe,"dn=1",new CountNameClassPairCallbackHandler());
    template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,new String[0],new DefaultIncrementalAttributesMapper());
    template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,new DefaultIncrementalAttributesMapper());
    template.search(jndiInjectMe,"dn=1",new DefaultIncrementalAttributesMapper());
    template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,new String[0],new LdapEntryIdentificationContextMapper());
    template.search(jndiInjectMe,"dn=1",SearchControls.OBJECT_SCOPE,new LdapEntryIdentificationContextMapper());
    template.search(jndiInjectMe,"dn=1",new LdapEntryIdentificationContextMapper());
    template.search(jndiInjectMe,"dn=1",searchControls,new LdapEntryIdentificationContextMapper());
    template.search(jndiInjectMe,"dn=1",searchControls, new DefaultIncrementalAttributesMapper());
}
 
Example 2
Source File: LdapUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static Name getDnOfEntry(LdapTemplate ldapTemplate, String baseDN,
    String objectClass, String filterAttributeName, String filterAttributeValue) {

    ContextMapper<Name> mapper =
        new AbstractContextMapper<Name>() {
            public Name doMapFromContext(DirContextOperations ctx) {
                return ctx.getDn();
            }
        };

    AndFilter filter = new AndFilter();
    filter.and(
        new EqualsFilter("objectclass", objectClass)).and(
            new EqualsFilter(filterAttributeName, filterAttributeValue));

    List<Name> result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, mapper);

    if (result != null && !result.isEmpty()) {
        //not only the first one....
        return result.get(0);
    }
    return null;
}
 
Example 3
Source File: TestContextSourceFactoryBeanTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerStartup() throws Exception {
    ctx = new ClassPathXmlApplicationContext("/applicationContext-testContextSource.xml");
    LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class);
    assertThat(ldapTemplate).isNotNull();

    List<String> list = ldapTemplate.search(
            LdapQueryBuilder.query().where("objectclass").is("person"),
            new AttributesMapper<String>() {
                public String mapFromAttributes(Attributes attrs)
                        throws NamingException {
                    return (String) attrs.get("cn").get();
                }
            });
    assertThat(list.size()).isEqualTo(5);
}
 
Example 4
Source File: EmbeddedLdapServerFactoryBeanTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerStartup() throws Exception {
    ctx = new ClassPathXmlApplicationContext("/applicationContext-ldifPopulator.xml");
    LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class);
    assertThat(ldapTemplate).isNotNull();

    List<String> list = ldapTemplate.search(
            LdapQueryBuilder.query().where("objectclass").is("person"),
            new AttributesMapper<String>() {
                public String mapFromAttributes(Attributes attrs)
                        throws NamingException {
                    return (String) attrs.get("cn").get();
                }
            });
    assertThat(list.size()).isEqualTo(5);
}
 
Example 5
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 6
Source File: LdapUpgradeExtension.java    From zstack with Apache License 2.0 5 votes vote down vote up
private void update(LdapTemplate ldapTemplate, LdapAccountRefVO ref){
    String uid = ref.getLdapUid();

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("uid", ref.getLdapUid()));

    List<Object> result = ldapTemplate.search("", filter.toString(), new AbstractContextMapper<Object>() {
        @Override
        protected Object doMapFromContext(DirContextOperations ctx) {
            return ctx.getNameInNamespace();
        }
    });

    if(result.size() == 0){
        logger.error(String.format("Can not find ldapUid[%s] dn", uid));
        return;
    }

    if(result.size() > 1){
        logger.error(String.format("ldapUid[%s] More than one dn result", uid));
        return;
    }

    String dn = result.get(0).toString();
    ref.setLdapUid(dn);
    dbf.update(ref);
    logger.info(String.format("update ldapUid[%s] to ldapDn[%s] success", uid, dn));
}
 
Example 7
Source File: LdapUtil.java    From zstack with Apache License 2.0 5 votes vote down vote up
void findLdapDnMemberOfList(LdapTemplate ldapTemplate, String ldapDn, List<String> resultDnList, List<String> dnIgnoreList){
    if(dnIgnoreList.contains(ldapDn)){
        return;
    }

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter(getMemberKey(), ldapDn));

    List<Object> groupList = ldapTemplate.search("", filter.toString(), new AbstractContextMapper<Object>() {
        @Override
        protected Object doMapFromContext(DirContextOperations ctx) {
            return ctx.getNameInNamespace();
        }
    });

    if(groupList.isEmpty()){
        dnIgnoreList.add(ldapDn);
        return;
    }

    for(Object groupObj : groupList){
        if(groupObj == null || !(groupObj instanceof String)){
            continue;
        }

        String groupDn = (String)groupObj;

        if(resultDnList.contains(groupDn)){
            continue;
        }

        resultDnList.add(groupDn);
        findLdapDnMemberOfList(ldapTemplate, groupDn, resultDnList, dnIgnoreList);
    }
}
 
Example 8
Source File: LdapUtil.java    From zstack with Apache License 2.0 5 votes vote down vote up
private String getFullUserDn(LdapTemplate ldapTemplate, String filter) {
    String dn;
    try {
        List<Object> result = ldapTemplate.search("", filter, new AbstractContextMapper<Object>() {
            @Override
            protected Object doMapFromContext(DirContextOperations ctx) {
                return ctx.getNameInNamespace();
            }
        });
        if (result.size() == 1) {
            dn = result.get(0).toString();
        } else if (result.size() > 1) {
            throw new OperationFailureException(err(
                    LdapErrors.UNABLE_TO_GET_SPECIFIED_LDAP_UID, "More than one ldap search result"));
        } else {
            return "";
        }
        logger.info(String.format("getDn success filter:%s, dn:%s", filter, dn));
    } catch (NamingException e) {
        LdapServerVO ldapServerVO = getLdapServer();
        throw new OperationFailureException(err(
                LdapErrors.UNABLE_TO_GET_SPECIFIED_LDAP_UID, "You'd better check the LDAP/AD server[url:%s, baseDN:%s, encryption:%s, username:%s, password:******]" +
                        " configuration and test connection first.getDn error filter:%s",
                ldapServerVO.getUrl(), ldapServerVO.getBase(),
                ldapServerVO.getEncryption(), ldapServerVO.getUsername(), filter));
    }
    return dn;
}
 
Example 9
Source File: UserServiceImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static Map<String, Attribute> getAttributesOfEntry(LdapTemplate ldapTemplate, String baseDN,
                                                           String objectClass, String searchFilter,
                                                           String[] searchAttributes) {

    Map<String, Attribute> ldapAttributes = null;

    AttributesMapper<Map<String, Attribute>> mapper =
        new AttributesMapper<Map<String, Attribute>>() {
        public Map<String, Attribute> mapFromAttributes(Attributes attrs) throws NamingException {
            Map<String, Attribute> map = new HashMap<>();
            NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
            while (attrEnum.hasMore()) {
                Attribute att = attrEnum.next();
                map.put(att.getID(), att);
            }
            return map;
        }
    };

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", objectClass)).and(new HardcodedFilter(searchFilter));

    List<?> result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
    if (result != null && !result.isEmpty()) {
        ldapAttributes = CastUtils.cast((Map<?, ?>)result.get(0));
    }

    return ldapAttributes;
}
 
Example 10
Source File: LdapUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Map<String, Attribute> getAttributesOfEntry(LdapTemplate ldapTemplate, String baseDN,
    String objectClass, String filterAttributeName, String filterAttributeValue,
    String[] searchAttributes) {

    Map<String, Attribute> ldapAttributes = null;

    AttributesMapper<Map<String, Attribute>> mapper =
        new AttributesMapper<Map<String, Attribute>>() {
            public Map<String, Attribute> mapFromAttributes(Attributes attrs) throws NamingException {
                Map<String, Attribute> map = new HashMap<>();
                NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
                while (attrEnum.hasMore()) {
                    Attribute att = attrEnum.next();
                    map.put(att.getID(), att);
                }
                return map;
            }
        };

    List<?> result = null;
    AndFilter filter = new AndFilter();
    filter.and(
            new EqualsFilter("objectclass", objectClass)).and(
                    new EqualsFilter(filterAttributeName, filterAttributeValue));

    result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
    if (result != null && !result.isEmpty()) {
        ldapAttributes = CastUtils.cast((Map<?, ?>)result.get(0));
    }

    return ldapAttributes;
}
 
Example 11
Source File: LdapUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static List<String> getAttributeOfEntries(
    LdapTemplate ldapTemplate, String baseDN,
    String objectClass, List<Filter> filters,
    String searchAttribute) {

    List<String> ldapAttributes = null;

    AttributesMapper<Object> mapper =
        new AttributesMapper<Object>() {
        public Object mapFromAttributes(Attributes attrs) throws NamingException {
            NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
            while (attrEnum.hasMore()) {
                return attrEnum.next().get();
            }
            return null;
        }
    };

    String[] searchAttributes = new String[] {searchAttribute};

    List<?> result = null;
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectclass", objectClass));
    if (filters != null) {
        for (Filter f : filters) {
            filter.and(f);
        }
    }

    result = ldapTemplate.search((baseDN == null) ? "" : baseDN, filter.toString(),
        SearchControls.SUBTREE_SCOPE, searchAttributes, mapper);
    if (result != null && !result.isEmpty()) {
        ldapAttributes = CastUtils.cast((List<?>)result);
    }

    return ldapAttributes;
}
 
Example 12
Source File: EmbeddedLdapServerFactoryBeanTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
  public void testServerStartup() throws Exception {
      ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
      LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class);
      assertNotNull(ldapTemplate);

List<String> list = ldapTemplate.search(
		LdapQueryBuilder.query().where("objectclass").is("person"),
		new AttributesMapper<String>() {
			public String mapFromAttributes(Attributes attrs)
					throws NamingException {
				return (String) attrs.get("cn").get();
			}
		});
      assertEquals(5, list.size());
  }
 
Example 13
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 14
Source File: LdapOperationsImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public <T> List<T> search(LdapTemplate ldapTemplate, LdapQuery query, AttributesMapper<T> mapper)
{
    return ldapTemplate.search(query, mapper);
}