对于 Spring,将“java.naming.ldap.attributes.binary”属性注入 ldapTemplate
@Bean
public LdapTemplate ldapTemplate() {
return new LdapTemplate(contextSource());
}
@Bean
public ContextSource contextSource() {
final LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl(env.getRequiredProperty("ldap.url"));
contextSource.setBase(env.getRequiredProperty("ldap.base"));
contextSource.setUserDn(env.getRequiredProperty("ldap.user"));
contextSource.setPassword(env.getRequiredProperty("ldap.password"));
// Important!!! Tell ldapTemplate to retrieve AD field
// "objectGUID" as binary. Otherwise it will be
// retrieved as a String, thus, modifying the byte[] array
final Map<String, Object> envProps = new HashMap<>();
envProps.put("java.naming.ldap.attributes.binary","objectGUID");
contextSource.setBaseEnvironmentProperties(envProps);
return contextSource;
}
...
// Will not complain about the String to byte[] conversion and
// Has to be 16 in length. If not, you did something
// wrong. For example ldapTemplate still retrieves objectGUID
// as String, modifying the value
byte[] guidBytes = (byte[]) attributes.get("objectGUID").get();
if (guidBytes.length == 16) {
// Convert encoded AD objectGUID to UUID
// objectGUID is not storing bits sequentially, so do the dance
UUID uuid = UUID.fromString(
String.format("%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
guidBytes[3] & 255,
guidBytes[2] & 255,
guidBytes[1] & 255,
guidBytes[0] & 255,
guidBytes[5] & 255,
guidBytes[4] & 255,
guidBytes[7] & 255,
guidBytes[6] & 255,
guidBytes[8] & 255,
guidBytes[9] & 255,
guidBytes[10] & 255,
guidBytes[11] & 255,
guidBytes[12] & 255,
guidBytes[13] & 255,
guidBytes[14] & 255,
guidBytes[15] & 255));
}