Java源码示例:org.springframework.ldap.core.support.AbstractContextMapper

示例1
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);
}
 
示例2
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;
}
 
示例3
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;
}
 
示例4
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;
}
 
示例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;
}
 
示例6
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));
}
 
示例7
@Test(expected = IncorrectResultSizeDataAccessException.class)
public void testSearchForObjectWithMultipleHits() {
	tested.searchForObject(BASE_STRING, "(&(objectclass=person)(sn=*))", new AbstractContextMapper() {
		@Override
		protected Object doMapFromContext(DirContextOperations ctx) {
			return ctx;
		}
	});
}
 
示例8
@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;
		}
	});
}
 
示例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;
		}
	});
}
 
示例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;
		}
	});
}
 
示例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());
    }
}
 
示例12
/**
 * 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);
}