虽然凭据验证有效,但组成员身份验证无效。
我假设组成员身份是 ldap 的组合base and userDn.
这是一个可以帮助您的代码。
public class LDAPDetail{
private String url; //your LDAP url
private Long timeout; // some timeout to connect LDAP
private String domain; // domain of user
private String userContainer; // typically value for OU=**,dc=**,dc=**
// You should be getting value for _domain_ and _userContainer_ from user's LDAP detail
}
public void validateUserDetails(){
LdapDetail ldapDetail = //gets user's value which you want to validate.
LdapTemplate ldapTemplate = build(ldapDetail, "username", "password");
AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("cn", userName));
ldapTemplate.authenticate(LdapUtils.emptyLdapName(), filter.toString(), "password")
}
public static LdapTemplate build(LdapDetail ldapDetail, String userName, String password) {
LdapContextSource ldapContextSource = new LdapContextSource();
ldapContextSource.setBase(ldapDetail.getUserContainer());
ldapContextSource.setUrl(ldapDetail.getUrl());
ldapContextSource.setAnonymousReadOnly(true);
ldapContextSource.setCacheEnvironmentProperties(false);
ldapContextSource.setUserDn(ldapDetail.getDomain());
ldapContextSource.setBaseEnvironmentProperties(buildContextFor(ldapDetail, userName, password));
LdapTemplate ldapTemplate = new LdapTemplate(ldapContextSource);
ldapTemplate.setContextSource(ldapContextSource);
return ldapTemplate;
}
public static Map<String, Object> buildContextFor(LdapDetail ldapDetail, String userName, String password) {
Map<String, Object> env = new HashMap<>();
env.put(Context.REFERRAL, "throw");
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put("java.naming.factory.url.pkgs",
"org.jboss.naming:org.jnp.interfaces:org.jboss.naming:org.jnp.interfaces");
env.put("com.sun.jndi.ldap.connect.timeout", String.valueOf(ldapDetail.getTimeout()));
env.put(Context.PROVIDER_URL, ldapDetail.getUrl());
env.put("ldap.domain", ldapDetail.getDomain());
env.put(Context.SECURITY_PRINCIPAL, userName);
env.put(Context.SECURITY_CREDENTIALS, password);
return env;
}