spring-ldap-core(Spring LDAP 函式庫)存在的意義,和 Spring JDBC 對數據庫的意義如出一轍。
JNDI 之於 LDAP 編程,正如 JDBC 之於 SQL 編程。兩套 API 風格迥異、各有優缺點,卻共享同樣的痛點:
Spring JDBC 用 JdbcTemplate 解決了第一個問題,Spring LDAP 給出的答案就是 LdapTemplate。
<bean id="contextSourceTarget" class="org.springframework.ldap.core.support.LdapContextSource">
<property name="url" value="ldap://localhost:10389" />
<property name="base" value="dc=example,dc=com" />
<property name="userDn" value="uid=admin,ou=system" />
<property name="password" value="secret" />
</bean>
<bean id="contextSource" class="org.springframework.ldap.transaction.compensating.manager.TransactionAwareContextSourceProxy">
<constructor-arg ref="contextSourceTarget" />
</bean>
<bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
<constructor-arg ref="contextSource" />
</bean>
配置完成後,即可在程式中注入 ldapTemplate 進行操作。
DistinguishedName 實現了 Name 接口,提供了操作目錄的便利方法(該類已過時,官方推薦改用 javax.naming.ldap.LdapName)。構建任何操作時,都可以用它來生成基目錄:
private DistinguishedName buildDn() {
DistinguishedName dn = new DistinguishedName();
dn.append("ou", "People");
return dn;
}
更複雜的場景是按唯一 userId 查詢其 DN,這時需要組合過濾器:
protected Name getPeopleDn(String userId) {
AndFilter andFilter = new AndFilter();
andFilter.and(new EqualsFilter("objectclass", "person"));
andFilter.and(new EqualsFilter("objectclass", "xUserObjectClass"));
andFilter.and(new EqualsFilter("uid", userId));
List<Name> result = ldapTemplate.search(buildDn(), andFilter.encode(),
SearchControls.SUBTREE_SCOPE, new AbstractContextMapper() {
@Override
protected Name doMapFromContext(DirContextOperations adapter) {
return adapter.getDn();
}
});
if (null == result || result.size() != 1) {
throw new UserNotFoundException();
} else {
return result.get(0);
}
}
DN 限制的是目錄位置,過濾器限制的是屬性條件。AndFilter 是「與」過濾器,EqualsFilter 是相等過濾器,此外還有 WhitespaceWildcardsFilter、LikeFilter、GreaterThanOrEqualsFilter、LessThanOrEqualsFilter 等內建實現可自由組合。
查詢有兩個入口:不知道 DN 時用 search 做子樹搜索,已知 DN 時用 lookup 直接取出條目。
List<DistinguishedName> result = ldapTemplate.search(buildDn(), filter.encode(),
SearchControls.SUBTREE_SCOPE, new AbstractContextMapper() {
@Override
protected DistinguishedName doMapFromContext(DirContextOperations adapter) {
return (DistinguishedName) adapter.getDn();
}
});
下面則是直接取出 Entry,第二個參數可選,用來指定需要的屬性:
public Account queryUser(String userId) {
return (Account) ldapTemplate.lookup(getPeopleDn(userId),
new String[] { "uid", "cn", "objectClass" },
new AccountAttributesMapper());
}
private class AccountAttributesMapper implements AttributesMapper {
public Object mapFromAttributes(Attributes attrs) throws NamingException {
Account person = new Account();
person.setUserID((String) attrs.get("uid").get());
person.setUserName((String) attrs.get("cn").get());
person.setDescription((String) attrs.get("description").get());
return person;
}
}
AttributesMapper 的地位等同 JDBC 中的 RowMapper,負責把 LDAP 屬性映射成物件。
如果嫌 AttributesMapper 取屬性囉嗦,Spring 還提供了上下文映射基類,程式碼優雅不少:
public Account queryUser(String userId) {
return (Account) ldapTemplate.lookup(getPeopleDn(userId),
new String[] { "uid", "cn", "objectClass" },
new AccountContextMapper());
}
private class AccountContextMapper extends AbstractContextMapper {
private String[] ldapAttrId;
@SuppressWarnings("unchecked")
public AccountContextMapper() {
ldapAttrId = buildAttr(userAttrService.getLdapAttrIds(),
new String[] { "uid", "cn", "objectClass" });
}
@Override
public Object doMapFromContext(DirContextOperations context) {
Account account = new Account();
account.setUserId(context.getStringAttribute("uid"));
account.setUserName(context.getStringAttribute("cn"));
Map<String, Object> userAttributes = new HashMap<String, Object>();
for (String ldapAttr : ldapAttrId) {
Object value;
Object[] values = context.getObjectAttributes(ldapAttr);
if (values == null || values.length == 0) continue;
value = (values.length == 1) ? values[0] : values;
if (value instanceof String && StringUtils.isEmpty(value.toString())) continue;
userAttributes.put(ldapAttr, value);
}
account.setUserAttributes(userAttributes);
return account;
}
}
真正需要關注的只有 doMapFromContext,其餘程式碼只是「取哪些屬性」的附加配置。
插入資料需要兩件事:確定存放目錄(DN)與準備屬性。DN 用前面的方法構造,屬性則用 DirContextAdapter 承載:
DirContextAdapter context = new DirContextAdapter(dn);
context.setAttributeValues("objectclass", userLdapObjectClasses.split(","));
context.setAttributeValue("uid", account.getUserId());
mapToContext(account, context);
ldapTemplate.bind(context);
bind 是綁定的核心 API。LDAP 屬性是有型別的:單值用 setAttributeValue,多值用 setAttributeValues。mapToContext 是自行擴充的映射方法:
protected void mapToContext(Account account, DirContextOperations ctx) {
ctx.setAttributeValue("cn", account.getUserName());
ctx.setAttributeValue("sn", account.getUserName());
ctx.setAttributeValue("user-account-time", getDateStr(account.getLifeTime(), "yyyy/MM/dd"));
if (StringUtils.isNotEmpty(account.getPassword())) {
ctx.setAttributeValue("userPassword", account.getPassword());
}
Map<String, Object> userAttributes = account.getUserAttributes();
for (Map.Entry<String, Object> o : userAttributes.entrySet()) {
String ldapAtt = userAttrService.getLdapAttrId(o.getKey());
if (ldapAtt == null) throw new RuntimeException("Invalid attribute " + o.getKey());
if (o.getValue() == null) continue;
if (o.getValue() instanceof String && StringUtils.isWhitespace(o.getValue().toString())) continue;
if (ObjectUtils.isArray(o.getValue()) && !(o.getValue() instanceof byte[])) {
Object[] array = ObjectUtils.toObjectArray(o.getValue());
if (array != null && array.length != 0) ctx.setAttributeValues(ldapAtt, array);
} else if (o.getValue() instanceof List) {
Object[] array = ((List) o.getValue()).toArray();
if (array != null && array.length != 0) ctx.setAttributeValues(ldapAtt, array);
} else {
ctx.setAttributeValue(ldapAtt, o.getValue());
}
}
}
解綁非常直接:
ldapTemplate.unbind(dn);
先取出 Entry,改屬性,再交給 modifyAttributes 提交:
DirContextOperations context = ldapTemplate.lookupContext(dn);
context.setAttributeValue("user-status", status);
ldapTemplate.modifyAttributes(context);
Spring 支援 Entry 移動,同時引入「重命名策略」概念,內建兩種:DefaultTempEntryRenamingStrategy 在條目末尾加後綴生成副本(cn=john doe, ou=users 會生成 cn=john doe_temp, ou=users,後綴可透過 tempSuffix 配置,默認 _temp);DifferentSubtreeTempEntryRenamingStrategy 則把臨時 DN 放到獨立子樹下,由 subtreeNode 配置。策略配置在 ContextSourceTransactionManager 的 renamingStrategy 屬性上:
<bean id="ldapRenameStrategy"
class="org.springframework.ldap.transaction.compensating.support.DifferentSubtreeTempEntryRenamingStrategy">
<constructor-arg name="subtreeNode" value="ou=People,dc=temp,dc=com,dc=cn"></constructor-arg>
</bean>
這一切的前提是目錄伺服器支援移動;否則只能用「刪除 + 插入」模擬:
DirContextAdapter newContext = new DirContextAdapter(newDn);
DirContextOperations oldContext = ldapTemplate.lookupContext(oldDn);
NamingEnumeration<? extends Attribute> attrs = oldContext.getAttributes().getAll();
try {
while (attrs.hasMore()) {
Attribute attr = attrs.next();
newContext.getAttributes().put(attr);
}
} catch (NamingException e) {
throw new RuntimeException("remove entry error:" + e.getMessage());
}
ldapTemplate.unbind(oldDn);
ldapTemplate.bind(newContext);
遺憾的是部分 LDAP 伺服器不支援分頁,而支援者可以透過 PagedResultsControl 以 cookie 完成分頁交互:
public PagedResult getAllPersons(PagedResultsCookie cookie) {
PagedResultsRequestControl control = new PagedResultsRequestControl(PAGE_SIZE, cookie);
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
List persons = ldapTemplate.search("", "objectclass=person", searchControls, control);
return new PagedResult(persons, control.getCookie());
}
典型的 JDBC 事務配置:
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
服務層用 @Transactional 即可標注事務。若需要單獨管理 LDAP 事務,配置 ContextSourceTransactionManager 並起別名 ldapTx:
<bean id="ldapTxManager" class="org.springframework.ldap.transaction.compensating.manager.ContextSourceTransactionManager">
<property name="contextSource" ref="contextSource" />
<qualifier value="ldapTx"/>
</bean>
使用時寫 @Transactional("ldapTx");若不想每次寫別名,可自訂註解:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.transaction.annotation.Transactional;
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Transactional("ldapTx")
public @interface LdapTransactional { }
若同一個服務裡 JDBC 與 LDAP 都要動,則配置 ContextSourceAndDataSourceTransactionManager 統一管理:
<bean id="ldapJdbcTxManager"
class="org.springframework.ldap.transaction.compensating.manager.ContextSourceAndDataSourceTransactionManager">
<property name="contextSource" ref="contextSource"/>
<property name="dataSource" ref="dataSource" />
<qualifier value="ldapJdbcTx"/>
</bean>
正如資料庫領域有 ORM 把表映射成 Java 物件,LDAP 操作同樣有 ODM(Object-Directory Mapping),把目錄條目映射成物件,進一步省去手寫 Mapper 的功夫。