Java Code Examples for org.springframework.ldap.core.support.AbstractContextMapper

The following examples show how to use org.springframework.ldap.core.support.AbstractContextMapper. 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: Spring-5.0-Projects   Source File: LdapAuthRepositoryCustomImpl.java    License: MIT License 6 votes vote down vote up
private String getDnForUser(String uid) {
  List<String> result = ldapTemplate.search(
      LdapQueryBuilder.query().where("uid").is(uid),
      new AbstractContextMapper<String>() {
         protected String doMapFromContext(DirContextOperations ctx) {
        	 logger.info("######## NameInNamespace -->"+ctx.getNameInNamespace());
            return ctx.getNameInNamespace();
         }
      });

  if(result.size() != 1) {
    throw new RuntimeException("User not found or not unique");
  }

  return result.get(0);
}
 
Example 2
Source Project: cxf   Source File: LdapUtils.java    License: 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 Project: spring-ldap   Source File: LdapTreeBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private LdapTree getLdapTree(final DirContextOperations rootContext) {
	final LdapTree ldapTree = new LdapTree(rootContext);
	ldapTemplate.listBindings(rootContext.getDn(),
			new AbstractContextMapper<Object>() {
				@Override
				protected Object doMapFromContext(DirContextOperations ctx) {
					Name dn = ctx.getDn();
					dn = LdapUtils.prepend(dn, rootContext.getDn());
					ldapTree.addSubTree(getLdapTree(ldapTemplate
							.lookupContext(dn)));
					return null;
				}
			});

	return ldapTree;
}
 
Example 4
Source Project: spring-ldap   Source File: LdapTreeBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private LdapTree getLdapTree(final DirContextOperations rootContext) {
	final LdapTree ldapTree = new LdapTree(rootContext);
	ldapTemplate.listBindings(rootContext.getDn(),
			new AbstractContextMapper<Object>() {
				@Override
				protected Object doMapFromContext(DirContextOperations ctx) {
					Name dn = ctx.getDn();
					dn = LdapUtils.prepend(dn, rootContext.getDn());
					ldapTree.addSubTree(getLdapTree(ldapTemplate
							.lookupContext(dn)));
					return null;
				}
			});

	return ldapTree;
}
 
Example 5
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 Project: zstack   Source File: LdapUpgradeExtension.java    License: 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 Project: spring-ldap   Source File: LdapTemplateSearchResultITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = IncorrectResultSizeDataAccessException.class)
public void testSearchForObjectWithMultipleHits() {
	tested.searchForObject(BASE_STRING, "(&(objectclass=person)(sn=*))", new AbstractContextMapper() {
		@Override
		protected Object doMapFromContext(DirContextOperations ctx) {
			return ctx;
		}
	});
}
 
Example 8
Source Project: spring-ldap   Source File: LdapTemplateSearchResultITest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = EmptyResultDataAccessException.class)
public void testSearchForObjectNoHits() {
	tested.searchForObject(BASE_STRING, "(&(objectclass=person)(sn=Person does not exist))", new AbstractContextMapper() {
		@Override
		protected Object doMapFromContext(DirContextOperations ctx) {
			return ctx;
		}
	});
}
 
Example 9
@Test(expected = IncorrectResultSizeDataAccessException.class)
public void testSearchForObjectWithMultipleHits() {
	tested.searchForObject(BASE_STRING, "(&(objectclass=person)(sn=*))", new AbstractContextMapper() {
		@Override
		protected Object doMapFromContext(DirContextOperations ctx) {
			return ctx;
		}
	});
}
 
Example 10
@Test(expected = EmptyResultDataAccessException.class)
public void testSearchForObjectNoHits() {
	tested.searchForObject(BASE_STRING, "(&(objectclass=person)(sn=Person does not exist))", new AbstractContextMapper() {
		@Override
		protected Object doMapFromContext(DirContextOperations ctx) {
			return ctx;
		}
	});
}
 
Example 11
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 12
Source Project: spring-ldap   Source File: InvalidBackslashITest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Test for LDAP-109, LDAP-50. When an entry has a distinguished name
 * including a backslach ('\') the Name supplied to DefaultDirObjectFactory
 * will be invalid.
 * <p>
 * E.g. the distinguished name "cn=Some\\Person6,ou=company1,ou=Sweden"
 * (indicating that the cn value is 'Some\Person'), will be represented by a
 * <code>CompositeName</code> with the string representation
 * "cn=Some\\\Person6,ou=company1,ou=Sweden", which is in fact an invalid DN.
 * This will be supplied to <code>DistinguishedName</code> for parsing,
 * causing it to fail. This test makes sure that Spring LDAP properly works
 * around this bug.
 * </p>
 * <p>
 * What happens under the covers is (in the Java LDAP Provider code):
 * 
 * <pre>
 * LdapName ldapname = new LdapName(&quot;cn=Some\\\\Person6,ou=company1,ou=Sweden&quot;);
 * CompositeName compositeName = new CompositeName();
 * compositeName.add(ldapname.get(ldapname.size() - 1)); // for some odd reason
 * </pre>
 * <code>CompositeName#add()</code> cannot handle this and the result is
 * the spoiled DN.
 * </p>
 * @throws InvalidNameException
 */
@Test
   @Category(NoAdTest.class)
public void testSearchForDnSpoiledByCompositeName() throws InvalidNameException {
	List result = tested.search("", "(sn=Person6)", new AbstractContextMapper() {
		@Override
		protected Object doMapFromContext(DirContextOperations ctx) {
			LdapName dn = (LdapName) ctx.getDn();
               Rdn rdn = LdapUtils.getRdn(dn, "cn");
               assertThat(dn.toString()).isEqualTo("cn=Some\\\\Person6,ou=company1,ou=Sweden");
			assertThat(rdn.getValue()).isEqualTo("Some\\Person6");
			return new Object();
		}
	});

	assertThat(result).hasSize(1);
}