CAS 在默认情况下仅提供了返回用户名给客户端的。但鉴于一些客户端系统在登录回来获取用户信息时,username不能唯一确定一个用户,可能用户名+工号、地区编号+用户名等各种各样的情况。因此,我们需要对CAS-service 进行扩展。对,没错,cas必然有考虑这一点。cas提供了配置的方式给我们方便的去返回更多用户的信息,但由于配置始终具备一定的局限性,所以我们自己实现这个功能。
1.我们先看看cas的基本实现。从实现中看到,确实只返回了username
<!-- deployerConfigContext.xml -->
<bean id="attributeRepository" class="org.jasig.services.persondir.support.NamedStubPersonAttributeDao"
p:backingMap-ref="attrRepoBackingMap" />
<util:map id="attrRepoBackingMap">
<entry key="uid" value="uid" />
<entry key="eduPersonAffiliation" value="eduPersonAffiliation" />
<entry key="groupMembership" value="groupMembership" />
<entry>
<key><value>memberOf</value></key>
<list>
<value>faculty</value>
<value>staff</value>
<value>org</value>
</list>
</entry>
</util:map>
public class NamedStubPersonAttributeDao extends StubPersonAttributeDao {
public NamedStubPersonAttributeDao() {
}
public NamedStubPersonAttributeDao(Map backingMap) {
super(backingMap);
}
public final Set<IPersonAttributes> getPeopleWithMultivaluedAttributes(Map<String, List<Object>> query) {
List list = (List)query.get("username");
HashMap m = new HashMap(this.getBackingMap());
m.put("username", list);
this.setBackingMap(m);
return super.getPeopleWithMultivaluedAttributes(query);
}
}
2.必然要把原始实现先注释掉
3.添加自定义实现配置
<!-- deployerConfigContext.xml -->
<bean id="attributeRepository" class="com.ucap.igsd.cas.handler.UserStubPersonAttributeDao" p:accountDao-ref="accountDao" />
4.实现UserStubPersonAttributeDao
public class UserStubPersonAttributeDao extends StubPersonAttributeDao {
public AccountDao accountDao;
@Override
public IPersonAttributes getPerson(String uid) {
Map<String, List<Object>> attributes = new HashMap<String, List<Object>>();
try {
Account account = accountDao.getAccountInfo(uid);
attributes.put("username", Collections.singletonList((Object)URLEncoder.encode(account.getUserName(), "UTF-8")));
attributes.put("email", Collections.singletonList((Object)URLEncoder.encode(account.getEmail(), "UTF-8")));
attributes.put("phone", Collections.singletonList((Object)URLEncoder.encode(account.getPhone(), "UTF-8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return new AttributeNamedPersonImpl(attributes);
}
public AccountDao getAccountDao() {
return accountDao;
}
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
}