cas-sample-site1/2各配上一个用于显示我们是否能够成功后用户信息的index.jsp

在同一个域名下如taobao.com下会有多个商铺(就是租户)好比:

 

  • taobao.com/company_101/张飞
  • taobao.com/company_102/张飞
  • taobao.com/company_103/赵云

看张飞这个名字,看!!!

 

不同的company(租户)下有着相同的用户,但其实这是两个不用的用户,中国同名同姓的人多了去了,对吧,这时company_101的张飞登录是因该只看到它所属的company_101这个租户下所有的数据和信息吧,而不能跑到company_102中看到别人家的信息,对吧?

 

国外很多解决方案说是在我们的CAS SSO的配置文件里在绑定LDAP的context时写上多条这样的东西:

 

 
  1. <bean class=" org.sky.cas.auth.CASLDAPAuthenticationHandler"

  2. p:filter="uid=%u" p:searchBase="o=101,o=company,dc=sky,dc=org"

  3. p:contextSource-ref="contextSource" />

  4.  
  5. <bean class=" org.sky.cas.auth.CASLDAPAuthenticationHandler"

  6. p:filter="uid=%u" p:searchBase="o=102,o=company,dc=sky,dc=org"

  7. p:contextSource-ref="contextSource" />

  8.  
  9. <bean class=" org.sky.cas.auth.CASLDAPAuthenticationHandler"

  10. p:filter="uid=%u" p:searchBase="o=103,o=company,dc=sky,dc=org"

  11. p:contextSource-ref="contextSource" />


可是,我们想想:

 

  1. 我们的租户在我们的后台系统中是自动“开户”的,companyid是一个自动增加的,我从companyid_101现在增加到了companyid_110时,你是不是每次用户一开户,你就要去手动改这个CAS SSO中的配置文件呢?
  2. 如果你不嫌烦,好好好,你够狠,你就手工改吧!但是当你每次在配置文件中新增一条配置语句时,你的CAS SSO是不是要断服务重启啊?那你还怎么做到24*7的这种不间断服务啊疑问

一般来说,我们的开户是用程序自动写入LDAP中去的,即LDAP中的company_101, company_102, company_103是由程序自动生成的,那我们的程序就需要能够让用户在登录后台B2B系统时自动可以根据用户选择的租户来为用户正确登录的这么一种自动识别功能,就好比下面这样的一个登录界面:

 

 

看到这个界面了吗?

 

对的,这个就是CAS SSO的主登录界面,我把它都给改了,还加入了支持多租户登录的功能,我们今天就要来讲这个功能是怎么做出来的,包括如何去定制自己的CAS SSO的登录界面。

 

再来看看用于今天练习的我们在LDAP中的组织结构是怎么样的吧。

看到上面这张图了吧,这就是我说的“多租户”的概念,大家应该记得我们在CAS SSO第二天中怎么去拿CAS SSO绑定LDAP中的一条UserDN然后去搜索的吧?

 

 
  1. <bean class=" org.sky.cas.auth.CASLDAPAuthenticationHandler"

  2. p:filter="uid=%u" p:searchBase="o=company,dc=sky,dc=org"

  3. p:contextSource-ref="contextSource" />

对吧!!!

 

 

现在我们要做到的就是:

p:searchBase="xxx.xxx.xx"

这条要做成动态的,比如说:

 

 

  • 用户是company_id=101的,这时这个p:searchBase就应该变为:“p:searchBase="uid=sky,o=101,o=company,dc=sky,dc=org"
  • 用户是company_id=102的,这时这个p:searchBase就应该变为:“p:searchBase="uid=jason,o=102,o=company,dc=sky,dc=org"

 

前面我们提到过,这些配置是放在XML文件中的,因此每次增加一个”租户“我们要手工在XML配置文件中新增一条,这个不现实,它是实现不了我们的24*7的这种服务的要求的,我们要做的是可以让这个p:searchBase能够动态的去组建这个userDN,所以重点是要解决这个问题。

 

该问题在国外的YALE CAS论坛上有两种解决方案:

 

  • 一种是直接通过CAS的登录界面然后在输入用户名时要求用户以这种形式“uid=sky,o=101"去输入它的用户名,这种做法先不去说会造成用户登录时的困扰,而且CAS SSO的登录界面也不支持这样格式的用户名输入。
  • 一种就是很笨的在CAS SSO的配置文件中绑定多个p:searchBase,这个方法已经被我们否掉了。

因此,笔者在这边要提的将是独创的可以做到全动态的去根据用户名,密码和所该用户所属组织自动在后台创建p:searchBase的最完美的解决方案,下面我们就开始吧。

 

创建工程

我们这次是要在CAS SSO这个产品上做扩展了,为此,我们不能再像我们第一天和第二天中那样直接拿个文本编辑器去改CAS SSO里的配置文件了,我们需要创建一个eclipse工程,来看我们的eclipse工程。

 

 

look,今天我们把这个cas-server放到了eclipse工程中去了,然后在eclipse里随改随测试,现在我们就来讲述如何创建这个工程以使得cas server可以运行在我们的eclipse的工程中。

因此我们在eclipse中新建一个java工程-是java工程你可千万不要建成j2ee工程啊,然后按照上图建立相应的目录。

 

CAS SERVER工程的组建

导入所有的配置文件

这是我们在第一天,第二天中布署在tomcat下的cas server工程的目录:

 

D:\tomcat\webapps\cas-server\WEB-INF\classes

 

把这个目录下所有的内容,除去以下2个目录:

  • org
  • META-INF

外所有的东西统统拷贝入eclipse中的cas-server工程中的src/main/resources目录下

 

构建WEB-INF目录

将D:\tomcat\webapps\cas-server\WEB-INF目录下这几个目录放入cas-server工程的src/main/webapp/WEB-INF目录下

 

 

 

构建cas-server基本源码

解压开我们下载的”cas-server-3.5.2-release"包,内含源码,它位于这样的一个目录cas-server-3.5.2\cas-server-webapp\src\main\java“

 

将这个目录下所有的文件置于cas-server工程的src/main/java目录下

 

并在eclipse工程中做如下设置

 

此处需要注意的是我们把:

  • src/main/java
  • src/main/resources

这两个目录做成编译路径,而src/main/webapp不作为编译路径

 

别忘了把所有的src/main/webapp/WEB-INF/lib目录下的jar加到cas-server工程的Libraries中去。

 

 

构建webapp目录

将我们在第一天、第二天中布署在tomcat中的case-server中以下这些目录

拷贝到eclipse的cas-server工程中的src/main/webapp目录

 

CAS SSO在jboss/weblogic下的bug的修正

由于我们的eclipse中的cas-server将和我们的cas-sample-site1以及cas-sample-site2启动在jboss下,因此cas sso在jboss或者是在weblogic下有两个小问题,在此需要修正。

 

  1. META-INF文件内的persistence.xml中报HSQLDialect错误
  2. 报log4jConfiguration.xml文件在启动时找不到的错误

下面我们来看如何修正这两个小BUG。

 

修正CAS SSO的persistence.xml文件中的HSQLDialect错误

这是原始的/META-INF/persistence.xml文件的内容:

 
  1. <class>org.jasig.cas.services.AbstractRegisteredService</class>

  2. <class>org.jasig.cas.services.RegexRegisteredService</class>

  3. <class>org.jasig.cas.services.RegisteredServiceImpl</class>

  4. <class>org.jasig.cas.ticket.TicketGrantingTicketImpl</class>

  5. <class>org.jasig.cas.ticket.ServiceTicketImpl</class>

  6. <class>org.jasig.cas.ticket.registry.support.JpaLockingStrategy$Lock</class>


我们在文件最后加入以下配置代码

 
  1. <class>org.jasig.cas.services.AbstractRegisteredService</class>

  2. <class>org.jasig.cas.services.RegexRegisteredService</class>

  3. <class>org.jasig.cas.services.RegisteredServiceImpl</class>

  4. <class>org.jasig.cas.ticket.TicketGrantingTicketImpl</class>

  5. <class>org.jasig.cas.ticket.ServiceTicketImpl</class>

  6. <class>org.jasig.cas.ticket.registry.support.JpaLockingStrategy$Lock</class>

  7. <properties>

  8. <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />

  9. </properties>

这是完整的改完后的persistence.xml文件的内容:

 
  1. <persistence xmlns="http://java.sun.com/xml/ns/persistence"

  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  3. xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"

  4. version="2.0">

  5.  
  6. <persistence-unit name="CasPersistence" transaction-type="RESOURCE_LOCAL">

  7. <class>org.jasig.cas.services.AbstractRegisteredService</class>

  8. <class>org.jasig.cas.services.RegexRegisteredService</class>

  9. <class>org.jasig.cas.services.RegisteredServiceImpl</class>

  10. <class>org.jasig.cas.ticket.TicketGrantingTicketImpl</class>

  11. <class>org.jasig.cas.ticket.ServiceTicketImpl</class>

  12. <class>org.jasig.cas.ticket.registry.support.JpaLockingStrategy$Lock</class>

  13. <properties>

  14. <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />

  15. </properties>

  16. </persistence-unit>

  17. </persistence>

 

改完后请保存。

 

修正CAS SSO中log4jConfiguration.xml文件在启动时找不到的错误

找到eclipse的cas-server工程中WEB-INF/spring-configuration/log4jConfiguration.xml文件,将这段内容注释掉

 
  1. <bean id="log4jInitialization" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">

  2. <property name="targetClass" value="org.springframework.util.Log4jConfigurer"/>

  3. <property name="targetMethod" value="initLogging"/>

  4. <property name="arguments">

  5. <list>

  6. <value>${log4j.config.location:classpath:log4j.xml}</value>

  7. <value>${log4j.refresh.interval:60000}</value>

  8. </list>

  9. </property>

  10. </bean>

 

整个log4jConfiguration.xml文件修改后是这个样子的:

 
  1. <beans xmlns="http://www.springframework.org/schema/beans"

  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  3. xmlns:p="http://www.springframework.org/schema/p"

  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  5.  
  6.  
  7. <!--

  8. <bean id="log4jInitialization" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">

  9. <property name="targetClass" value="org.springframework.util.Log4jConfigurer"/>

  10. <property name="targetMethod" value="initLogging"/>

  11. <property name="arguments">

  12. <list>

  13. <value>${log4j.config.location:classpath:log4j.xml}</value>

  14. <value>${log4j.refresh.interval:60000}</value>

  15. </list>

  16. </property>

  17. </bean>

  18. -->

  19. </beans>


改完后请保存。

 

将CAS-SERVER从eclipse java工程改为j2ee工程

右键单击cas-sso工程,选择project properties,然后选择project facet,按照如下截图来做选择。

 

组装可在eclipse中启动的cas-server web工程

右键单击cas-sso工程,选择project properties,然后选择Deployment Assembly,这个基本功我已经在 通向架构师的道路(第二十天)万能框架spring(二)maven结合spring与ibatis中详细讲述过这个Deployment Assembly是干什么用的了。

 

在eclipse中启动cas-server工程

一切无误后请在eclipse中启动cas-sso吧。

 

开始修改源码

如何让cas-server支持动态的p:searchBase呢

我们的p:searchBase从这一层o=company,dc=sky,dc=org开始要进行动态组装,因此我们将在deployConfiguration.xml文件中将我们的ldap的p:searchBase的绑定改成如下:

 

p:searchBase="o=company,dc=sky,dc=org",然后我们使用程序动态组建o=company,dc=sky,dc=org之前的内容到底是该“o=101”呢还是因该是“o=102” 这样的串。

 

为cas server的登录增加一个项

原来的cas sso的登录项只有两个属性:

  • username
  • password

我们需要增加一个companyid,用于判断当前登录的用户是属于哪个租户的。

新建CASCredential类

 
  1. public class CASCredential extends RememberMeUsernamePasswordCredentials {

  2. private static final long serialVersionUID = 1L;

  3.  
  4. private Map<String, Object> param;

  5.  
  6.  
  7. private String companyid;

  8.  
  9. /**

  10. * @return the companyid

  11. */

  12. public String getCompanyid() {

  13. return companyid;

  14. }

  15.  
  16. /**

  17. * @param companyid the companyid to set

  18. */

  19. public void setCompanyid(String companyid) {

  20. this.companyid = companyid;

  21. }

  22.  
  23. public Map<String, Object> getParam() {

  24. return param;

  25. }

  26.  
  27. public void setParam(Map<String, Object> param) {

  28. this.param = param;

  29. }

  30. }


这就是我们扩展的CASCredential类,该类除了拥有原来CAS SSO基本credential中的username和password两个属性外还有一个叫companyid的属性。

 

将新增的companyid绑定至cas sso的登录页面

修改src/main/webapp/WEB-INF/login-webflow.xml文件,找到以下这段:

 
  1. <view-state id="viewLoginForm" view="casLoginView" model="credentials">

  2. <binder>

  3. <binding property="username" />

  4. <binding property="password" />

  5. </binder>


将其改成:

 
  1. <view-state id="viewLoginForm" view="casLoginView" model="credentials">

  2. <binder>

  3. <binding property="username" />

  4. <binding property="password" />

  5. <binding property="companyid"/>

  6. </binder>

 

扩展CAS SSO登录页面的submit行为以支持我们在页面中新增的companyid属性可以被提交到CAS SSO的后台

新建一个类CASAuthenticationViaFormAction,内容如下:

 
  1. package org.sky.cas.auth;

  2.  
  3. import java.util.ArrayList;

  4. import java.util.HashMap;

  5. import java.util.List;

  6. import java.util.Map;

  7.  
  8. import javax.servlet.http.HttpServletRequest;

  9. import javax.servlet.http.HttpServletResponse;

  10. import javax.validation.constraints.NotNull;

  11.  
  12. import org.jasig.cas.CentralAuthenticationService;

  13. import org.jasig.cas.authentication.handler.AuthenticationException;

  14. import org.jasig.cas.authentication.principal.Credentials;

  15. import org.jasig.cas.authentication.principal.Service;

  16. import org.jasig.cas.ticket.TicketException;

  17. import org.jasig.cas.web.bind.CredentialsBinder;

  18. import org.jasig.cas.web.support.WebUtils;

  19. import org.slf4j.Logger;

  20. import org.slf4j.LoggerFactory;

  21. import org.springframework.binding.message.MessageBuilder;

  22. import org.springframework.binding.message.MessageContext;

  23. import org.springframework.util.StringUtils;

  24. import org.springframework.web.util.CookieGenerator;

  25. import org.springframework.webflow.core.collection.MutableAttributeMap;

  26. import org.springframework.webflow.execution.RequestContext;

  27.  
  28. @SuppressWarnings("deprecation")

  29. public class CASAuthenticationViaFormAction {

  30. /**

  31. * Binder that allows additional binding of form object beyond Spring

  32. * defaults.

  33. */

  34. private CredentialsBinder credentialsBinder;

  35.  
  36. /** Core we delegate to for handling all ticket related tasks. */

  37. @NotNull

  38. private CentralAuthenticationService centralAuthenticationService;

  39.  
  40. @NotNull

  41. private CookieGenerator warnCookieGenerator;

  42.  
  43. protected Logger logger = LoggerFactory.getLogger(getClass());

  44.  
  45. public final void doBind(final RequestContext context, final Credentials credentials) throws Exception {

  46. final HttpServletRequest request = WebUtils.getHttpServletRequest(context);

  47.  
  48. if (this.credentialsBinder != null && this.credentialsBinder.supports(credentials.getClass())) {

  49. this.credentialsBinder.bind(request, credentials);

  50. }

  51. }

  52.  
  53. public final String submit(final RequestContext context, final Credentials credentials, final MessageContext messageContext)

  54. throws Exception {

  55. String companyid = "";

  56. // Validate login ticket

  57. final String authoritativeLoginTicket = WebUtils.getLoginTicketFromFlowScope(context);

  58. final String providedLoginTicket = WebUtils.getLoginTicketFromRequest(context);

  59. if (credentials instanceof CASCredential) {

  60. String companyCode = "compnayid";

  61. CASCredential rmupc = (CASCredential) credentials;

  62. companyid = rmupc.getCompanyid();

  63.  
  64. }

  65.  
  66. if (!authoritativeLoginTicket.equals(providedLoginTicket)) {

  67. this.logger.warn("Invalid login ticket " + providedLoginTicket);

  68. final String code = "INVALID_TICKET";

  69. messageContext.addMessage(new MessageBuilder().error().code(code).arg(providedLoginTicket).defaultText(code).build());

  70. return "error";

  71. }

  72.  
  73. final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);

  74. final Service service = WebUtils.getService(context);

  75. if (StringUtils.hasText(context.getRequestParameters().get("renew")) && ticketGrantingTicketId != null && service != null) {

  76.  
  77. try {

  78. final String serviceTicketId = this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicketId,

  79. service, credentials);

  80. WebUtils.putServiceTicketInRequestScope(context, serviceTicketId);

  81. putWarnCookieIfRequestParameterPresent(context);

  82. return "warn";

  83. } catch (final TicketException e) {

  84. if (isCauseAuthenticationException(e)) {

  85. populateErrorsInstance(e, messageContext);

  86. return getAuthenticationExceptionEventId(e);

  87. }

  88.  
  89. this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicketId);

  90. if (logger.isDebugEnabled()) {

  91. logger.debug("Attempted to generate a ServiceTicket using renew=true with different credentials", e);

  92. }

  93. }

  94. }

  95.  
  96. try {

  97.  
  98. CASCredential rmupc = (CASCredential) credentials;

  99. WebUtils.putTicketGrantingTicketInRequestScope(context,

  100. centralAuthenticationService.createTicketGrantingTicket(rmupc));

  101. putWarnCookieIfRequestParameterPresent(context);

  102.  
  103. return "success";

  104. } catch (final TicketException e) {

  105. populateErrorsInstance(e, messageContext);

  106. if (isCauseAuthenticationException(e))

  107. return getAuthenticationExceptionEventId(e);

  108. return "error";

  109. }

  110. }

  111.  
  112. private void populateErrorsInstance(final TicketException e, final MessageContext messageContext) {

  113.  
  114. try {

  115. messageContext.addMessage(new MessageBuilder().error().code(e.getCode()).defaultText(e.getCode()).build());

  116. } catch (final Exception fe) {

  117. logger.error(fe.getMessage(), fe);

  118. }

  119. }

  120.  
  121. private void putWarnCookieIfRequestParameterPresent(final RequestContext context) {

  122. final HttpServletResponse response = WebUtils.getHttpServletResponse(context);

  123.  
  124. if (StringUtils.hasText(context.getExternalContext().getRequestParameterMap().get("warn"))) {

  125. this.warnCookieGenerator.addCookie(response, "true");

  126. } else {

  127. this.warnCookieGenerator.removeCookie(response);

  128. }

  129. }

  130.  
  131. private AuthenticationException getAuthenticationExceptionAsCause(final TicketException e) {

  132. return (AuthenticationException) e.getCause();

  133. }

  134.  
  135. private String getAuthenticationExceptionEventId(final TicketException e) {

  136. final AuthenticationException authEx = getAuthenticationExceptionAsCause(e);

  137.  
  138. if (this.logger.isDebugEnabled())

  139. this.logger.debug("An authentication error has occurred. Returning the event id " + authEx.getType());

  140.  
  141. return authEx.getType();

  142. }

  143.  
  144. private boolean isCauseAuthenticationException(final TicketException e) {

  145. return e.getCause() != null && AuthenticationException.class.isAssignableFrom(e.getCause().getClass());

  146. }

  147.  
  148. public final void setCentralAuthenticationService(final CentralAuthenticationService centralAuthenticationService) {

  149. this.centralAuthenticationService = centralAuthenticationService;

  150. }

  151.  
  152. /**

  153. * Set a CredentialsBinder for additional binding of the HttpServletRequest

  154. * to the Credentials instance, beyond our default binding of the

  155. * Credentials as a Form Object in Spring WebMVC parlance. By the time we

  156. * invoke this CredentialsBinder, we have already engaged in default binding

  157. * such that for each HttpServletRequest parameter, if there was a JavaBean

  158. * property of the Credentials implementation of the same name, we have set

  159. * that property to be the value of the corresponding request parameter.

  160. * This CredentialsBinder plugin point exists to allow consideration of

  161. * things other than HttpServletRequest parameters in populating the

  162. * Credentials (or more sophisticated consideration of the

  163. * HttpServletRequest parameters).

  164. *

  165. * @param credentialsBinder the credentials binder to set.

  166. */

  167. public final void setCredentialsBinder(final CredentialsBinder credentialsBinder) {

  168. this.credentialsBinder = credentialsBinder;

  169. }

  170.  
  171. public final void setWarnCookieGenerator(final CookieGenerator warnCookieGenerator) {

  172. this.warnCookieGenerator = warnCookieGenerator;

  173. }

  174. }


这个类很简单,主要是第59行到第64行的:

 
  1. if (credentials instanceof CASCredential) {

  2. String companyCode = "compnayid";

  3. CASCredential rmupc = (CASCredential) credentials;

  4. companyid = rmupc.getCompanyid();

  5.  
  6. }


以及第98行到第100行的:

 
  1. CASCredential rmupc = (CASCredential) credentials;

  2. WebUtils.putTicketGrantingTicketInRequestScope(context,

  3. centralAuthenticationService.createTicketGrantingTicket(rmupc));

它告诉了CAS SSO使用我们自定义的CASCredential来验证用户在CAS SSO中的登录信息,而不是原来CAS SSO默认的UsernameAndPasswordCredential。

 

把”CASAuthenticationViaFormAction“类注册给CAS SSO,告诉CAS SSO在登录页面点击”登录“按钮后能够使用这个我们自定义的submit action:

 

修改配置文件:src/main/webapp/WEB-INF/cas-servlet.xml

找到以下这行:

 
  1. <bean id="authenticationViaFormAction" class="org.jasig.cas.web.flow.AuthenticationViaFormAction"

  2. p:centralAuthenticationService-ref="centralAuthenticationService"

  3. p:warnCookieGenerator-ref="warnCookieGenerator"/>

把它注释掉改成:

 
  1. <!-- <bean id="authenticationViaFormAction" class="org.jasig.cas.web.flow.AuthenticationViaFormAction"

  2. p:centralAuthenticationService-ref="centralAuthenticationService"

  3. p:warnCookieGenerator-ref="warnCookieGenerator"/>

  4. -->

  5.  
  6. <bean id="authenticationViaFormAction"

  7. class="org.sky.cas.auth.CASAuthenticationViaFormAction"

  8. p:centralAuthenticationService-ref="centralAuthenticationService"

  9. p:warnCookieGenerator-ref="warnCookieGenerator" />


此时,CAS SSO的登录界面在用户点击submit按钮时,就会使用我们自定义的这个CASAuthenticationViaFormAction类了。
 

增加p:searchBase使得CAS SSO的LDAP可以根据不同的companyid动态搜索用户的功能

新增一个类CASLDAPAuthenticationHandler,代码如下:

 

 
  1. package org.sky.cas.auth;

  2.  
  3. import org.jasig.cas.adaptors.ldap.AbstractLdapUsernamePasswordAuthenticationHandler;

  4. import org.jasig.cas.authentication.handler.AuthenticationException;

  5. import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;

  6. import org.jasig.cas.util.LdapUtils;

  7. import org.springframework.ldap.NamingSecurityException;

  8. import org.springframework.ldap.core.ContextSource;

  9. import org.springframework.ldap.core.LdapTemplate;

  10. import org.springframework.ldap.core.NameClassPairCallbackHandler;

  11. import org.springframework.ldap.core.SearchExecutor;

  12.  
  13. import javax.naming.NameClassPair;

  14. import javax.naming.NamingEnumeration;

  15. import javax.naming.NamingException;

  16. import javax.naming.directory.DirContext;

  17. import javax.naming.directory.SearchControls;

  18. import javax.validation.constraints.Max;

  19. import javax.validation.constraints.Min;

  20. import java.util.ArrayList;

  21. import java.util.List;

  22.  
  23. public class CASLDAPAuthenticationHandler extends AbstractLdapUsernamePasswordAuthenticationHandler {

  24. /** The default maximum number of results to return. */

  25. private static final int DEFAULT_MAX_NUMBER_OF_RESULTS = 1000;

  26.  
  27. /** The default timeout. */

  28. private static final int DEFAULT_TIMEOUT = 1000;

  29.  
  30. /** The search base to find the user under. */

  31. private String searchBase;

  32.  
  33. /** The scope. */

  34. @Min(0)

  35. @Max(2)

  36. private int scope = SearchControls.ONELEVEL_SCOPE;

  37.  
  38. /** The maximum number of results to return. */

  39. private int maxNumberResults = DEFAULT_MAX_NUMBER_OF_RESULTS;

  40.  
  41. /** The amount of time to wait. */

  42. private int timeout = DEFAULT_TIMEOUT;

  43.  
  44. /** Boolean of whether multiple accounts are allowed. */

  45. private boolean allowMultipleAccounts;

  46.  
  47. protected final boolean authenticateUsernamePasswordInternal(final UsernamePasswordCredentials credentials)

  48. throws AuthenticationException {

  49. CASCredential rmupc = (CASCredential) credentials;

  50. final String companyid = rmupc.getCompanyid();

  51. final List<String> cns = new ArrayList<String>();

  52.  
  53. final SearchControls searchControls = getSearchControls();

  54.  
  55. final String transformedUsername = getPrincipalNameTransformer().transform(credentials.getUsername());

  56. final String filter = LdapUtils.getFilterWithValues(getFilter(), transformedUsername);

  57. try {

  58. this.getLdapTemplate().search(new SearchExecutor() {

  59. public NamingEnumeration executeSearch(final DirContext context) throws NamingException {

  60. String baseDN = "";

  61. if (companyid != null && companyid.trim().length() > 0) {

  62. baseDN = "o=" + companyid + "," + searchBase;

  63. } else {

  64. baseDN = searchBase;

  65. }

  66. //System.out.println("searchBase=====" + baseDN);

  67. return context.search(baseDN, filter, searchControls);

  68. }

  69. }, new NameClassPairCallbackHandler() {

  70.  
  71. public void handleNameClassPair(final NameClassPair nameClassPair) {

  72. cns.add(nameClassPair.getNameInNamespace());

  73. }

  74. });

  75. } catch (Exception e) {

  76. log.error("search ldap error casue: " + e.getMessage(), e);

  77. return false;

  78. }

  79. if (cns.isEmpty()) {

  80. log.debug("Search for " + filter + " returned 0 results.");

  81. return false;

  82. }

  83. if (cns.size() > 1 && !this.allowMultipleAccounts) {

  84. log.warn("Search for " + filter + " returned multiple results, which is not allowed.");

  85. return false;

  86. }

  87.  
  88. for (final String dn : cns) {

  89. DirContext test = null;

  90. String finalDn = composeCompleteDnToCheck(dn, credentials);

  91. try {

  92. this.log.debug("Performing LDAP bind with credential: " + dn);

  93. test = this.getContextSource().getContext(finalDn, getPasswordEncoder().encode(credentials.getPassword()));

  94.  
  95. if (test != null) {

  96. return true;

  97. }

  98. } catch (final NamingSecurityException e) {

  99. log.debug("Failed to authenticate user {} with error {}", credentials.getUsername(), e.getMessage());

  100. return false;

  101. } catch (final Exception e) {

  102. this.log.error(e.getMessage(), e);

  103. return false;

  104. } finally {

  105. LdapUtils.closeContext(test);

  106. }

  107. }

  108.  
  109. return false;

  110. }

  111.  
  112. protected String composeCompleteDnToCheck(final String dn, final UsernamePasswordCredentials credentials) {

  113. return dn;

  114. }

  115.  
  116. private SearchControls getSearchControls() {

  117. final SearchControls constraints = new SearchControls();

  118. constraints.setSearchScope(this.scope);

  119. constraints.setReturningAttributes(new String[0]);

  120. constraints.setTimeLimit(this.timeout);

  121. constraints.setCountLimit(this.maxNumberResults);

  122.  
  123. return constraints;

  124. }

  125.  
  126. /**

  127. * Method to return whether multiple accounts are allowed.

  128. * @return true if multiple accounts are allowed, false otherwise.

  129. */

  130. protected boolean isAllowMultipleAccounts() {

  131. return this.allowMultipleAccounts;

  132. }

  133.  
  134. /**

  135. * Method to return the max number of results allowed.

  136. * @return the maximum number of results.

  137. */

  138. protected int getMaxNumberResults() {

  139. return this.maxNumberResults;

  140. }

  141.  
  142. /**

  143. * Method to return the scope.

  144. * @return the scope

  145. */

  146. protected int getScope() {

  147. return this.scope;

  148. }

  149.  
  150. /**

  151. * Method to return the search base.

  152. * @return the search base.

  153. */

  154. protected String getSearchBase() {

  155. return this.searchBase;

  156. }

  157.  
  158. /**

  159. * Method to return the timeout.

  160. * @return the timeout.

  161. */

  162. protected int getTimeout() {

  163. return this.timeout;

  164. }

  165.  
  166. public final void setScope(final int scope) {

  167. this.scope = scope;

  168. }

  169.  
  170. /**

  171. * @param allowMultipleAccounts The allowMultipleAccounts to set.

  172. */

  173. public void setAllowMultipleAccounts(final boolean allowMultipleAccounts) {

  174. this.allowMultipleAccounts = allowMultipleAccounts;

  175. }

  176.  
  177. /**

  178. * @param maxNumberResults The maxNumberResults to set.

  179. */

  180. public final void setMaxNumberResults(final int maxNumberResults) {

  181. this.maxNumberResults = maxNumberResults;

  182. }

  183.  
  184. /**

  185. * @param searchBase The searchBase to set.

  186. */

  187. public final void setSearchBase(final String searchBase) {

  188. this.searchBase = searchBase;

  189. }

  190.  
  191. /**

  192. * @param timeout The timeout to set.

  193. */

  194. public final void setTimeout(final int timeout) {

  195. this.timeout = timeout;

  196. }

  197.  
  198. /**

  199. * Sets the context source for LDAP searches. This method may be used to

  200. * support use cases like the following:

  201. * <ul>

  202. * <li>Pooling of LDAP connections used for searching (e.g. via instance

  203. * of {@link org.springframework.ldap.pool.factory.PoolingContextSource}).</li>

  204. * <li>Searching with client certificate credentials.</li>

  205. * </ul>

  206. * <p>

  207. * If this is not defined, the context source defined by

  208. * {@link #setContextSource(ContextSource)} is used.

  209. *

  210. * @param contextSource LDAP context source.

  211. */

  212. public final void setSearchContextSource(final ContextSource contextSource) {

  213. setLdapTemplate(new LdapTemplate(contextSource));

  214. }

  215.  
  216. }


这个类的作用就是给src/main/webapp/WEB-INF/deployerConfiguration.xml中以下这段用的:

 
  1. <property name="authenticationHandlers">

  2. <list>

  3.  
  4. <bean

  5. class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"

  6. p:httpClient-ref="httpClient" />

  7.  
  8. <bean class=" org.sky.cas.auth.CASLDAPAuthenticationHandler"

  9. p:filter="uid=%u" p:searchBase="o=company,dc=sky,dc=org"

  10. p:contextSource-ref="contextSource" />

  11. </list>

  12. </property>


请注意代码50行处:

final String companyid = rmupc.getCompanyid();


以及59行到69行处:

 
  1. public NamingEnumeration executeSearch(final DirContext context) throws NamingException {

  2. String baseDN = "";

  3. if (companyid != null && companyid.trim().length() > 0) {

  4. baseDN = "o=" + companyid + "," + searchBase;

  5. } else {

  6. baseDN = searchBase;

  7. }

  8. //System.out.println("searchBase=====" + baseDN);

  9. return context.search(baseDN, filter, searchControls);

  10. }

  11. }, new NameClassPairCallbackHandler() {


这就是在根据用户在登录界面中选择的companyid不同,而动态的去重组这个searchBase,以使得这个searchBase可以是o=101,o=company,dc=sky,dc=org, 也可以是o=102,o=company,dc=sky,dc=org同时它也可以变成o=103,o=company,dc=sky,dc=org。

 

有了这个类我们要修改我们的src/main/webapp/WEB-INF/deployerConfiguration.xml文件了,注意这个bean中的写法 ,已经被我修改掉了

 
  1. <bean id="authenticationManager" class="org.jasig.cas.authentication.AuthenticationManagerImpl">

  2.  
  3.  
  4. <property name="credentialsToPrincipalResolvers">

  5. <list>

  6. <bean class="org.sky.cas.auth.CASCredentialsToPrincipalResolver">

  7. <property name="attributeRepository" ref="attributeRepository" />

  8. </bean>

  9. </list>

  10. </property>

  11.  
  12.  
  13. <property name="authenticationHandlers">

  14. <list>

  15.  
  16. <bean

  17. class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"

  18. p:httpClient-ref="httpClient" />

  19.  
  20. <bean class=" org.sky.cas.auth.CASLDAPAuthenticationHandler"

  21. p:filter="uid=%u" p:searchBase="o=company,dc=sky,dc=org"

  22. p:contextSource-ref="contextSource" />

  23. </list>

  24. </property>

  25. </bean>

 

看到这个CASLDAPAuthenticationHandler类在这边的作用了吧。

 

将LDAP中登录用户的其它信息也带入到客户端登录成功后跳转的页面中去

我们知道,CAS SSO可以把username(uid)带入到客户端登录成功后的页面中去,可是一个uid在LDAP中还关联着许多其它有用的信息如:email。 还有就是我们刚才新增的companyid,我们也想把这些信息同时带到客户端登录成功的画面中去呢?

 

这边就需要使用到CAS SSO中的一个特殊的属性,它叫attributeRepository。

attributeRepository的作用

attributeRepository关联着一个dao和一个resolver,它们的作用如下:

  • attributeDAO是用于根据searchBase在LDAP中定位到一条数据,然后把该条数据所有的属性取出来用的一个工具类
  • credentialsToPrincipalResolvers,该类用于向客户端(就是我们的cas-samples-site1/site2)返回用户在CAS SSO中登录画面中输入的登录相关信息用的一个工具类

先来说attributeDAO的作用吧。

 

CASLdapPersonAttributeDao

比如说我们这边想要把ldap中某个uid的mail属性也带给到客户端中去

我们就要按照下面这段代码来书写CASLdapPersonAttributeDao类,该类扩展自”AbstractQueryPersonAttributeDao“类,它被置于”package org.jasig.services.persondir.support.ldap“包中,因为该包中还有其它相关的此类需要”引用"的工具类,我们不想到处import来import去了,因此直接把这个我们自定义的attributeDao类就直接放置于该包中了。

 

但是,嘿嘿嘿,在package org.jasig.services.persondir.support.ldap包中没有其它这个类需要引用的那些外部类,如下图所示:

 

 

怎么办?

 

很简单,直接找到cas-server 3.5.2的源码,将这两个外部类置于我们自定义的CASLdapPersonAttributeDao同一层的包路径下即可,我会在本文结束后直接给出完整的eclipse中可运行的cas-server的全部源码。

 

 
  1. /**

  2. * Licensed to Jasig under one or more contributor license

  3. * agreements. See the NOTICE file distributed with this work

  4. * for additional information regarding copyright ownership.

  5. * Jasig licenses this file to you under the Apache License,

  6. * Version 2.0 (the "License"); you may not use this file

  7. * except in compliance with the License. You may obtain a

  8. * copy of the License at:

  9. *

  10. * http://www.apache.org/licenses/LICENSE-2.0

  11. *

  12. * Unless required by applicable law or agreed to in writing,

  13. * software distributed under the License is distributed on

  14. * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY

  15. * KIND, either express or implied. See the License for the

  16. * specific language governing permissions and limitations

  17. * under the License.

  18. */

  19.  
  20. package org.jasig.services.persondir.support.ldap;

  21.  
  22. import java.util.ArrayList;

  23. import java.util.List;

  24. import java.util.Map;

  25. import java.util.Set;

  26. import java.util.regex.Matcher;

  27. import java.util.regex.Pattern;

  28.  
  29. import javax.naming.directory.SearchControls;

  30.  
  31. import org.apache.commons.lang.StringUtils;

  32. import org.apache.commons.logging.Log;

  33. import org.apache.commons.logging.LogFactory;

  34. import org.jasig.cas.util.CASCredentialHelper;

  35. import org.jasig.services.persondir.IPersonAttributes;

  36. import org.jasig.services.persondir.support.AbstractQueryPersonAttributeDao;

  37. import org.jasig.services.persondir.support.CaseInsensitiveAttributeNamedPersonImpl;

  38. import org.jasig.services.persondir.support.CaseInsensitiveNamedPersonImpl;

  39. import org.jasig.services.persondir.support.QueryType;

  40. import org.sky.cas.auth.LdapPersonInfoBean;

  41. import org.springframework.beans.factory.BeanCreationException;

  42. import org.springframework.beans.factory.InitializingBean;

  43. import org.springframework.ldap.core.AttributesMapper;

  44. import org.springframework.ldap.core.ContextSource;

  45. import org.springframework.ldap.core.LdapTemplate;

  46. import org.springframework.ldap.filter.EqualsFilter;

  47. import org.springframework.ldap.filter.Filter;

  48. import org.springframework.ldap.filter.LikeFilter;

  49. import org.springframework.util.Assert;

  50.  
  51. /**

  52. * LDAP implementation of {@link org.jasig.services.persondir.IPersonAttributeDao}.

  53. *

  54. * In the case of multi valued attributes a {@link java.util.List} is set as the value.

  55. *

  56. * <br>

  57. * <br>

  58. * Configuration:

  59. * <table border="1">

  60. * <tr>

  61. * <th align="left">Property</th>

  62. * <th align="left">Description</th>

  63. * <th align="left">Required</th>

  64. * <th align="left">Default</th>

  65. * </tr>

  66. * <tr>

  67. * <td align="right" valign="top">searchControls</td>

  68. * <td>

  69. * Set the {@link SearchControls} used for executing the LDAP query.

  70. * </td>

  71. * <td valign="top">No</td>

  72. * <td valign="top">Default instance with SUBTREE scope.</td>

  73. * </tr>

  74. * <tr>

  75. * <td align="right" valign="top">baseDN</td>

  76. * <td>

  77. * The base DistinguishedName to use when executing the query filter.

  78. * </td>

  79. * <td valign="top">No</td>

  80. * <td valign="top">""</td>

  81. * </tr>

  82. * <tr>

  83. * <td align="right" valign="top">contextSource</td>

  84. * <td>

  85. * A {@link ContextSource} from the Spring-LDAP framework. Provides a DataSource

  86. * style object that this DAO can retrieve LDAP connections from.

  87. * </td>

  88. * <td valign="top">Yes</td>

  89. * <td valign="top">null</td>

  90. * </tr>

  91. * <tr>

  92. * <td align="right" valign="top">setReturningAttributes</td>

  93. * <td>

  94. * If the ldap attributes set in the ldapAttributesToPortalAttributes Map should be copied

  95. * into the {@link SearchControls#setReturningAttributes(String[])}. Setting this helps reduce

  96. * wire traffic of ldap queries.

  97. * </td>

  98. * <td valign="top">No</td>

  99. * <td valign="top">true</td>

  100. * </tr>

  101. * <tr>

  102. * <td align="right" valign="top">queryType</td>

  103. * <td>

  104. * How multiple attributes in a query should be concatenated together. The other option is OR.

  105. * </td>

  106. * <td valign="top">No</td>

  107. * <td valign="top">AND</td>

  108. * </tr>

  109. * </table>

  110. *

  111. * @author andrew.petro@yale.edu

  112. * @author Eric Dalquist

  113. * @version $Revision$ $Date$

  114. * @since uPortal 2.5

  115. */

  116. public class CASLdapPersonAttributeDao extends AbstractQueryPersonAttributeDao<LogicalFilterWrapper> implements InitializingBean {

  117. private static final Pattern QUERY_PLACEHOLDER = Pattern.compile("\\{0\\}");

  118. private final static AttributesMapper MAPPER = new AttributeMapAttributesMapper();

  119. protected final Log logger = LogFactory.getLog(getClass());

  120. /**

  121. * The LdapTemplate to use to execute queries on the DirContext

  122. */

  123. private LdapTemplate ldapTemplate = null;

  124.  
  125. private String baseDN = "";

  126. private String queryTemplate = null;

  127. private ContextSource contextSource = null;

  128. private SearchControls searchControls = new SearchControls();

  129. private boolean setReturningAttributes = true;

  130. private QueryType queryType = QueryType.AND;

  131.  
  132. public CASLdapPersonAttributeDao() {

  133. this.searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

  134. this.searchControls.setReturningObjFlag(false);

  135. }

  136.  
  137. /* (non-Javadoc)

  138. * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()

  139. */

  140. public void afterPropertiesSet() throws Exception {

  141. final Map<String, Set<String>> resultAttributeMapping = this.getResultAttributeMapping();

  142. if (this.setReturningAttributes && resultAttributeMapping != null) {

  143. this.searchControls.setReturningAttributes(resultAttributeMapping.keySet().toArray(

  144. new String[resultAttributeMapping.size()]));

  145. }

  146.  
  147. if (this.contextSource == null) {

  148. throw new BeanCreationException("contextSource must be set");

  149. }

  150. }

  151.  
  152. /* (non-Javadoc)

  153. * @see org.jasig.services.persondir.support.AbstractQueryPersonAttributeDao#appendAttributeToQuery(java.lang.Object, java.lang.String, java.util.List)

  154. */

  155. @Override

  156. protected LogicalFilterWrapper appendAttributeToQuery(LogicalFilterWrapper queryBuilder, String dataAttribute,

  157. List<Object> queryValues) {

  158. if (queryBuilder == null) {

  159. queryBuilder = new LogicalFilterWrapper(this.queryType);

  160. }

  161.  
  162. for (final Object queryValue : queryValues) {

  163. String queryValueString = queryValue == null ? null : queryValue.toString();

  164.  
  165. LdapPersonInfoBean person = new LdapPersonInfoBean();

  166. //person = CASCredentialHelper.getPersoninfoFromCredential(queryValueString);

  167. //queryValueString = person.getUsername();

  168. person = CASCredentialHelper.getPersoninfoFromCredential(queryValueString);

  169. queryValueString=person.getUsername();

  170. if (StringUtils.isNotBlank(queryValueString)) {

  171. final Filter filter;

  172. if (!queryValueString.contains("*")) {

  173. filter = new EqualsFilter(dataAttribute, queryValueString);

  174. } else {

  175. filter = new LikeFilter(dataAttribute, queryValueString);

  176. }

  177. queryBuilder.append(filter);

  178. }

  179. }

  180.  
  181. return queryBuilder;

  182. }

  183.  
  184. /* (non-Javadoc)

  185. * @see org.jasig.services.persondir.support.AbstractQueryPersonAttributeDao#getPeopleForQuery(java.lang.Object, java.lang.String)

  186. */

  187.  
  188. @Override

  189. protected List<IPersonAttributes> getPeopleForQuery(LogicalFilterWrapper queryBuilder, String queryUserName) {

  190. LdapPersonInfoBean ldapPerson = new LdapPersonInfoBean();

  191. ldapPerson = CASCredentialHelper.getPersoninfoFromCredential(queryUserName);

  192. final String generatedLdapQuery = queryBuilder.encode();

  193. //If no query is generated return null since the query cannot be run

  194. if (StringUtils.isBlank(generatedLdapQuery)) {

  195. return null;

  196. }

  197.  
  198. //Insert the generated query into the template if it is configured

  199. final String ldapQuery;

  200. if (this.queryTemplate == null) {

  201. ldapQuery = generatedLdapQuery;

  202. } else {

  203. final Matcher queryMatcher = QUERY_PLACEHOLDER.matcher(this.queryTemplate);

  204. ldapQuery = queryMatcher.replaceAll(generatedLdapQuery);

  205. }

  206. String searchBase = "";

  207. if (ldapPerson.getCompanyid().trim().length() > 0) {

  208. searchBase = "o=" + ldapPerson.getCompanyid() + "," + baseDN;

  209. } else {

  210. searchBase = baseDN;

  211. }

  212. logger.info("searchBase=====" + searchBase);

  213. //Execute the query

  214. List<Map<String, List<Object>>> queryResults = new ArrayList<Map<String, List<Object>>>();

  215. try {

  216. queryResults = this.ldapTemplate.search(searchBase, ldapQuery, this.searchControls, MAPPER);

  217. } catch (Exception e) {

  218. logger.error(

  219. "search ldap with [searchBase===" + searchBase + "] [ldapQuery====" + ldapQuery + "], caused by: "

  220. + e.getMessage(), e);

  221. }

  222. final List<IPersonAttributes> peopleAttributes = new ArrayList<IPersonAttributes>(queryResults.size());

  223. for (final Map<String, List<Object>> queryResult : queryResults) {

  224. IPersonAttributes person;

  225. //if (ldapPerson.getUsername() != null) {

  226. if (queryUserName != null && queryUserName.trim().length() > 0) {

  227. //person = new CaseInsensitiveNamedPersonImpl(ldapPerson.getUsername(), queryResult);

  228. person = new CaseInsensitiveNamedPersonImpl(queryUserName, queryResult);

  229. } else {

  230. //Create the IPersonAttributes doing a best-guess at a userName attribute

  231. String userNameAttribute = this.getConfiguredUserNameAttribute();

  232. person = new CaseInsensitiveAttributeNamedPersonImpl(userNameAttribute, queryResult);

  233. }

  234.  
  235. peopleAttributes.add(person);

  236. }

  237.  
  238. return peopleAttributes;

  239. }

  240.  
  241. /**

  242. * @see javax.naming.directory.SearchControls#getTimeLimit()

  243. * @deprecated Set the property on the {@link SearchControls} and set that via {@link #setSearchControls(SearchControls)}

  244. */

  245. @Deprecated

  246. public int getTimeLimit() {

  247. return this.searchControls.getTimeLimit();

  248. }

  249.  
  250. /**

  251. * @see javax.naming.directory.SearchControls#setTimeLimit(int)

  252. * @deprecated

  253. */

  254. @Deprecated

  255. public void setTimeLimit(int ms) {

  256. this.searchControls.setTimeLimit(ms);

  257. }

  258.  
  259. /**

  260. * @return The base distinguished name to use for queries.

  261. */

  262. public String getBaseDN() {

  263. return this.baseDN;

  264. }

  265.  
  266. /**

  267. * @param baseDN The base distinguished name to use for queries.

  268. */

  269. public void setBaseDN(String baseDN) {

  270. if (baseDN == null) {

  271. baseDN = "";

  272. }

  273.  
  274. this.baseDN = baseDN;

  275. }

  276.  
  277. /**

  278. * @return The ContextSource to get DirContext objects for queries from.

  279. */

  280. public ContextSource getContextSource() {

  281. return this.contextSource;

  282. }

  283.  
  284. /**

  285. * @param contextSource The ContextSource to get DirContext objects for queries from.

  286. */

  287. public synchronized void setContextSource(final ContextSource contextSource) {

  288. Assert.notNull(contextSource, "contextSource can not be null");

  289. this.contextSource = contextSource;

  290. this.ldapTemplate = new LdapTemplate(this.contextSource);

  291. }

  292.  
  293. /**

  294. * Sets the LdapTemplate, and thus the ContextSource (implicitly).

  295. *

  296. * @param ldapTemplate the LdapTemplate to query the LDAP server from. CANNOT be NULL.

  297. */

  298. public synchronized void setLdapTemplate(final LdapTemplate ldapTemplate) {

  299. Assert.notNull(ldapTemplate, "ldapTemplate cannot be null");

  300. this.ldapTemplate = ldapTemplate;

  301. this.contextSource = this.ldapTemplate.getContextSource();

  302. }

  303.  
  304. /**

  305. * @return Search controls to use for LDAP queries

  306. */

  307. public SearchControls getSearchControls() {

  308. return this.searchControls;

  309. }

  310.  
  311. /**

  312. * @param searchControls Search controls to use for LDAP queries

  313. */

  314. public void setSearchControls(SearchControls searchControls) {

  315. Assert.notNull(searchControls, "searchControls can not be null");

  316. this.searchControls = searchControls;

  317. }

  318.  
  319. /**

  320. * @return the queryType

  321. */

  322. public QueryType getQueryType() {

  323. return queryType;

  324. }

  325.  
  326. /**

  327. * Type of logical operator to use when joining WHERE clause components

  328. *

  329. * @param queryType the queryType to set

  330. */

  331. public void setQueryType(QueryType queryType) {

  332. this.queryType = queryType;

  333. }

  334.  
  335. public String getQueryTemplate() {

  336. return this.queryTemplate;

  337. }

  338.  
  339. /**

  340. * Optional wrapper template for the generated part of the query. Use {0} as a placeholder for where the generated query should be inserted.

  341. */

  342. public void setQueryTemplate(String queryTemplate) {

  343. this.queryTemplate = queryTemplate;

  344. }

  345. }

 

注意206到211行处的写法

 
  1. String searchBase = "";

  2. if (ldapPerson.getCompanyid().trim().length() > 0) {

  3. searchBase = "o=" + ldapPerson.getCompanyid() + "," + baseDN;

  4. } else {

  5. searchBase = baseDN;

  6. }

  7. logger.info("searchBase=====" + searchBase);


 

 

CASLdapPersonAttributeDao类中需要使用到另外两个我们自定义的工具类代码如下:

 

CASCredentialHelper

 
  1. package org.jasig.cas.util;

  2.  
  3. import org.apache.commons.logging.Log;

  4. import org.apache.commons.logging.LogFactory;

  5.  
  6. import java.io.StringReader;

  7. import java.util.*;

  8. import org.jdom.*;

  9. import org.jdom.input.SAXBuilder;

  10. import org.jdom.xpath.*;

  11. import org.sky.cas.auth.LdapPersonInfoBean;

  12. import org.xml.sax.InputSource;

  13.  
  14. public class CASCredentialHelper {

  15. public final static Log logger = LogFactory.getLog(CASCredentialHelper.class);

  16.  
  17. public static LdapPersonInfoBean getPersoninfoFromCredential(String dnStr) {

  18. LdapPersonInfoBean person = new LdapPersonInfoBean();

  19. logger.debug("credential str======" + dnStr);

  20. try {

  21. if (dnStr != null) {

  22. //创建一个新的字符串

  23. String[] p_array = dnStr.split(",");

  24. if (p_array != null) {

  25. person.setCompanyid(p_array[1]);

  26. person.setUsername(p_array[0]);

  27. }

  28. }

  29. } catch (Exception e) {

  30. logger.error("get personinfo from DN: [:" + dnStr + "] error caused by: " + e.getMessage(), e);

  31. }

  32. return person;

  33. }

  34.  
  35. public static void main(String[] args) throws Exception {

  36. StringBuffer sb = new StringBuffer();

  37. sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");

  38. sb.append("<CASCredential>");

  39. sb.append("<result>");

  40. sb.append("<loginid>sys</loginid>");

  41. sb.append("<companyid>401</companyid>");

  42. sb.append("<email>aaa@a.net</email>");

  43. sb.append("</result>");

  44. sb.append("</CASCredential>");

  45. getPersoninfoFromCredential(sb.toString());

  46. }

  47. }


 

 

LdapPersonInfoBean

 
  1. package org.sky.cas.auth;

  2.  
  3. import java.io.Serializable;

  4.  
  5. public class LdapPersonInfoBean implements Serializable {

  6.  
  7. private String companyid = "";

  8. private String username = "";

  9.  
  10. /**

  11. * @return the companyid

  12. */

  13. public String getCompanyid() {

  14. return companyid;

  15. }

  16.  
  17. /**

  18. * @param companyid the companyid to set

  19. */

  20. public void setCompanyid(String companyid) {

  21. this.companyid = companyid;

  22. }

  23.  
  24. /**

  25. * @return the username

  26. */

  27. public String getUsername() {

  28. return username;

  29. }

  30.  
  31. /**

  32. * @param username the username to set

  33. */

  34. public void setUsername(String username) {

  35. this.username = username;

  36. }

  37. }


以上这两个类到底在干什么,大家不要急 ,我们接着看下面的这个CASCredentialsToPrincipalResolver类吧

CASCredentialsToPrincipalResolver类

该类的作用是这样的:

 

一个客户在CAS SSO登录界面登录了,然后输入了相关的登录信息,然后CAS SSO跳转到客户端的主界面中去,客户端在主界面通过以下语句:

 
  1. AttributePrincipal principal = (AttributePrincipal) req.getUserPrincipal();

  2. String userName = principal.getName();


即可以得到CAS SSO转发过来的合法登录了的用户名,可是,可是。。。CAS SSO默认只能带一个username过来给到客户端,而该成功登录了的用户的在LDAP中的其它属性是通过以下语句得到的:

 
  1. Map attributes = principal.getAttributes();

  2. String email = (String) attributes.get("email");

 

现在问题来了,我们新增的companyid即不是该用户在ldap中的一个属性,又不能在req.getUserPrincipal();中带过来,怎么办?

 

熊掌与鱼兼得法 ,既可以把用户在LDAP中其它属性带到客户端又可以把客户的登录信息也带到客户端

因此我们需要定制CASCredentialsToPrincipalResolver这个类,来看该类的代码:

 
  1. package org.sky.cas.auth;

  2.  
  3. import org.apache.commons.httpclient.UsernamePasswordCredentials;

  4. import org.apache.commons.logging.Log;

  5. import org.apache.commons.logging.LogFactory;

  6. import org.jasig.cas.authentication.principal.AbstractPersonDirectoryCredentialsToPrincipalResolver;

  7. import org.jasig.cas.authentication.principal.Credentials;

  8.  
  9. import java.io.ByteArrayOutputStream;

  10. import java.io.FileOutputStream;

  11. import java.io.IOException;

  12. import org.jdom.Document;

  13. import org.jdom.Element;

  14. import org.jdom.JDOMException;

  15. import org.jdom.output.Format;

  16. import org.jdom.output.XMLOutputter;

  17.  
  18. public class CASCredentialsToPrincipalResolver extends AbstractPersonDirectoryCredentialsToPrincipalResolver {

  19. public final Log logger = LogFactory.getLog(this.getClass());

  20.  
  21. protected String extractPrincipalId(final Credentials credentials) {

  22. final CASCredential casCredential = (CASCredential) credentials;

  23. return buildCompCredential(casCredential.getUsername(), casCredential.getCompanyid());

  24. }

  25.  
  26. /**

  27. * Return true if Credentials are UsernamePasswordCredentials, false

  28. * otherwise.

  29. */

  30. public boolean supports(final Credentials credentials) {

  31. return credentials != null && CASCredential.class.isAssignableFrom(credentials.getClass());

  32. }

  33.  
  34. public String buildCompCredential(String loginId, String companyId) {

  35. StringBuffer sb = new StringBuffer();

  36. sb.append(loginId).append(",");

  37. sb.append(companyId);

  38. return sb.toString();

  39. }

  40. }

注意第23行和buildCompCredential方法,大家来看这个类原先是继承自AbstractPersonDirectoryCredentialsToPrincipalResolver 类对吧,如果我们不自定这个类,CAS SSO有一个默认的Resolver,你们知道CAS SSO默认的这个Resolver是怎么写的吗?

 

大家可以自己跟一下原码,在原码中,它是这样写的:

 
  1. package org.sky.cas.auth;

  2.  
  3. import org.apache.commons.httpclient.UsernamePasswordCredentials;

  4. import org.apache.commons.logging.Log;

  5. import org.apache.commons.logging.LogFactory;

  6. import org.jasig.cas.authentication.principal.AbstractPersonDirectoryCredentialsToPrincipalResolver;

  7. import org.jasig.cas.authentication.principal.Credentials;

  8.  
  9. import java.io.ByteArrayOutputStream;

  10. import java.io.FileOutputStream;

  11. import java.io.IOException;

  12. import org.jdom.Document;

  13. import org.jdom.Element;

  14. import org.jdom.JDOMException;

  15. import org.jdom.output.Format;

  16. import org.jdom.output.XMLOutputter;

  17.  
  18. public class CASCredentialsToPrincipalResolver extends AbstractPersonDirectoryCredentialsToPrincipalResolver {

  19. public final Log logger = LogFactory.getLog(this.getClass());

  20.  
  21. protected String extractPrincipalId(final Credentials credentials) {

  22. final CASCredential casCredential = (CASCredential) credentials;

  23. return casCredential.getUsername();

  24. }

  25.  
  26. /**

  27. * Return true if Credentials are UsernamePasswordCredentials, false

  28. * otherwise.

  29. */

  30. }


看到了没有,它只返回了一个username,因此,我们把这个类扩展了一下,使得CAS SSO在登录成功后可以给客户端返回这样的一个字串:"username,companyid”。

 

通过这样的方法以使得当客户在登录时输入的那些并不属于LDAP库中存储的信息也能够被带到客户端中去,这样的话我们在客户端中如果通过以下这段代码:

 
  1. AttributePrincipal principal = (AttributePrincipal) req.getUserPrincipal();

  2. String userName = principal.getName();

 

去试图获取从CAS SSO中带来的登录信息时,客户端将会得到一个这样的字串“username,companyid”,因此我们只要再在客户端做一次简单的切割,即可将我们需要的登录信息进行剥离了,如下例子:

 

 
  1. String[] userAttri = userName.split(",");

  2. uinfo.setUserName(userAttri[0]);

  3. uinfo.setCompanyId(userAttri[1]);

 

最终版src/main/webapp/WEB-INF/deployerConfiguration.xml文件

有了attributeDao, 有了resolver,我们彻底来重新配置一下我们的deployerConfiguration.xml文件吧,来看下面的配置:

 

 
  1. <?xml version="1.0" encoding="UTF-8"?>

  2.  
  3.  
  4. <beans xmlns="http://www.springframework.org/schema/beans"

  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"

  6. xmlns:tx="http://www.springframework.org/schema/tx" xmlns:sec="http://www.springframework.org/schema/security"

  7. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd

  8. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd

  9. http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

  10.  
  11. <bean id="authenticationManager" class="org.jasig.cas.authentication.AuthenticationManagerImpl">

  12.  
  13.  
  14. <property name="credentialsToPrincipalResolvers">

  15. <list>

  16. <bean class="org.sky.cas.auth.CASCredentialsToPrincipalResolver">

  17. <property name="attributeRepository" ref="attributeRepository" />

  18. </bean>

  19. </list>

  20. </property>

  21.  
  22.  
  23. <property name="authenticationHandlers">

  24. <list>

  25.  
  26. <bean

  27. class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"

  28. p:httpClient-ref="httpClient" />

  29.  
  30. <bean class=" org.sky.cas.auth.CASLDAPAuthenticationHandler"

  31. p:filter="uid=%u" p:searchBase="o=company,dc=sky,dc=org"

  32. p:contextSource-ref="contextSource" />

  33. </list>

  34. </property>

  35. </bean>

  36. <!-- ldap datasource -->

  37. <bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource">

  38. <property name="password" value="secret" />

  39. <property name="pooled" value="true" />

  40. <property name="url" value="ldap://localhost:389" />

  41.  
  42. <!--管理员 -->

  43. <property name="userDn" value="cn=Manager,dc=sky,dc=org" />

  44. <property name="baseEnvironmentProperties">

  45. <map>

  46. <!-- Three seconds is an eternity to users. -->

  47. <entry key="com.sun.jndi.ldap.connect.timeout" value="60" />

  48. <entry key="com.sun.jndi.ldap.read.timeout" value="60" />

  49. <entry key="java.naming.security.authentication" value="simple" />

  50. </map>

  51. </property>

  52. </bean>

  53.  
  54.  
  55. <sec:user-service id="userDetailsService">

  56. <sec:user name="@@THIS SHOULD BE REPLACED@@" password="notused"

  57. authorities="ROLE_ADMIN" />

  58. </sec:user-service>

  59.  
  60.  
  61. <bean id="attributeRepository"

  62. class="org.jasig.services.persondir.support.ldap.CASLdapPersonAttributeDao">

  63. <property name="contextSource" ref="contextSource" />

  64. <property name="baseDN" value="o=company,dc=sky,dc=org" />

  65. <property name="requireAllQueryAttributes" value="true" />

  66. <property name="queryAttributeMapping">

  67. <map>

  68. <entry key="username" value="uid" />

  69. </map>

  70. </property>

  71. <property name="resultAttributeMapping">

  72. <map>

  73. <entry key="uid" value="loginid" />

  74. <entry key="mail" value="email" />

  75. </map>

  76. </property>

  77. </bean>

  78.  
  79. <bean id="serviceRegistryDao" class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl">

  80.  
  81. <property name="registeredServices">

  82. <list>

  83. <bean class="org.jasig.cas.services.RegexRegisteredService">

  84. <property name="id" value="0" />

  85. <property name="name" value="HTTP and IMAP" />

  86. <property name="description" value="Allows HTTP(S) and IMAP(S) protocols" />

  87. <property name="serviceId" value="^(https?|imaps?)://.*" />

  88. <property name="evaluationOrder" value="10000001" />

  89. <property name="ignoreAttributes" value="false" />

  90. <property name="allowedAttributes">

  91. <list>

  92. <value>loginid</value>

  93. <value>email</value>

  94. </list>

  95. </property>

  96. </bean>

  97.  
  98. </list>

  99. </property>

  100. </bean>

  101.  
  102. <bean id="auditTrailManager"

  103. class="com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager" />

  104.  
  105. <bean id="healthCheckMonitor" class="org.jasig.cas.monitor.HealthCheckMonitor">

  106. <property name="monitors">

  107. <list>

  108. <bean class="org.jasig.cas.monitor.MemoryMonitor"

  109. p:freeMemoryWarnThreshold="10" />

  110. <!-- NOTE The following ticket registries support SessionMonitor: * DefaultTicketRegistry

  111. * JpaTicketRegistry Remove this monitor if you use an unsupported registry. -->

  112. <bean class="org.jasig.cas.monitor.SessionMonitor"

  113. p:ticketRegistry-ref="ticketRegistry"

  114. p:serviceTicketCountWarnThreshold="5000"

  115. p:sessionCountWarnThreshold="100000" />

  116. </list>

  117. </property>

  118. </bean>

  119. </beans>


在这个配置文件里,我们把attributeDao还有Resolver还有我们的Ldap认证时用的AuthenticationHandler都变成了我们自定义的类了,但还是有2段配置代码大家看起来有些疑惑,没关系,我们接着来分析接着来变态:

 
  1. <bean id="attributeRepository"

  2. class="org.jasig.services.persondir.support.ldap.CASLdapPersonAttributeDao">

  3. <property name="contextSource" ref="contextSource" />

  4. <property name="baseDN" value="o=company,dc=sky,dc=org" />

  5. <property name="requireAllQueryAttributes" value="true" />

  6. <property name="queryAttributeMapping">

  7. <map>

  8. <entry key="username" value="uid" />

  9. </map>

  10. </property>

  11. <property name="resultAttributeMapping">

  12. <map>

  13. <entry key="uid" value="loginid" />

  14. <entry key="mail" value="email" />

  15. </map>

  16. </property>

  17. </bean>


看到这边的resultAttributeMapping,它的意思就是:根据 上面的“queryAttributeMapping”的这个键值找到ldap中该条数据,然后通过resultAttributeMapping返回给客户端 ,这段配置做的就是这么一件事。

 

注:

 

  • 一定要在queryAttributeMapping的entry key=后面写上"username”,这个username来自于我们cas sso登录主界面中的username这个属性。
  • 在resultAttributeMapping中key为LDAP中相关数据的“主键”,value就是我们希望让客户端通过以下代码获取到CAS SSO服务端传过来的值的那个key,千万不要搞错了哦。

 

 
  1. Map attributes = principal.getAttributes();

  2. String email = (String) attributes.get("email");

 

 

当然,到了这边,我们的值还不能直接返回给客户端 !!!

 

如果能够直接返回,到此处为止,我们的变态就应该已经全结束了,可是CAS SSO有着其严格的定义,不是说你要返回什么值给客户端你就可以返回的,还需要一个“allowed”。

 

继续看下去:

 

 
  1. <bean id="serviceRegistryDao" class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl">

  2.  
  3. <property name="registeredServices">

  4. <list>

  5. <bean class="org.jasig.cas.services.RegexRegisteredService">

  6. <property name="id" value="0" />

  7. <property name="name" value="HTTP and IMAP" />

  8. <property name="description" value="Allows HTTP(S) and IMAP(S) protocols" />

  9. <property name="serviceId" value="^(https?|imaps?)://.*" />

  10. <property name="evaluationOrder" value="10000001" />

  11. <property name="ignoreAttributes" value="false" />

  12. <property name="allowedAttributes">

  13. <list>

  14. <value>loginid</value>

  15. <value>email</value>

  16. </list>

  17. </property>

  18. </bean>

  19.  
  20. </list>

  21. </property>

  22. </bean>


看到这个地方了吗?

 
  1. <property name="allowedAttributes">

  2. <list>

  3. <value>loginid</value>

  4. <value>email</value>

  5. </list>

  6. </property>


这段XML配置的意思就是: 根据上面的“queryAttributeMapping”的这个键值找到ldap中该条数据,然后通过resultAttributeMapping返回给客户端,并且“允许“loginid”与"email“两个值可以通过客户端使用如下的的代码被允许访问得到:

 

 
  1. Map attributes = principal.getAttributes();

  2. String email = (String) attributes.get("email");


很烦? 不是,其实不烦,这是因为老外的框架做的严谨,而且扩展性好,只要通过extend, implement就可以实现我们自己的功能了,这种设计很强,或者说很变态,因为接下去还没完呢,哈哈,继续。

 

修改cas sso的主登录界面,把界面修改成如下风格

修改src/main/webapp/WEB-INF/view/jsp/default/ui/casLoginView.jsp

 

这个改页面,很简单,这个页面在:src/main/webapp/WEB-INF/view/default/ui/casLoginView.jsp

 

上手把这个页面的两个include去掉,如何去?如何增加以下这个下拉框:

 

 
  1. <select id="companyid" name="companyid" >

  2. <option value="101" selected>上海煤气公司</option>

  3. <option value="102" selected>上海自来水厂</option>

  4. <option value="103" selected>FBI</option>

  5. <option value="104" selected>神盾局</option>

  6. </select>

 

我在这边就不细说了,这属于copy & paste的工作,我在此就直接给出我自己制作完成后的casLoginView.jsp页面内所有的源码吧:

 
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  2. <%@ page session="true"%>

  3. <%@ page pageEncoding="utf-8"%>

  4. <%@ page contentType="text/html; charset=utf-8"%>

  5. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

  6. <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

  7. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

  8. <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

  9. <html>

  10. <head>

  11.  
  12. <link href="${pageContext.request.contextPath}/css/login.css"

  13. rel="stylesheet" type="text/css" />

  14. <link href="${pageContext.request.contextPath}/css/login_form.css"

  15. rel="stylesheet" type="text/css" />

  16.  
  17. <script language="javascript">

  18. var relativePath="<%=request.getContextPath()%>";

  19. </script>

  20. <title>CAS SSO登录</title>

  21. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

  22. </head>

  23. <body id="cas">

  24. <div style="text-align: center;">

  25.  
  26. </div>

  27. <form:form method="post" id="fm1" commandName="${commandName}"

  28. htmlEscape="true" style="height:300px">

  29. <div class="login_div" id="login">

  30. <table border="0" cellspacing="0" cellpadding="0">

  31. <tr>

  32. <td colspan="2" style="border-bottom: 1px solid #e5e9ee;"><img src="${pageContext.request.contextPath}/css/images/login_dot.png" width="24" height="24" hspace="5" align="absbottom" />登录</td>

  33. </tr>

  34. <tr>

  35. <td width="175" class="label"> 用户名:</td>

  36. <td width="405">

  37. <c:if test="${empty sessionScope.openIdLocalId}">

  38. <spring:message code="screen.welcome.label.netid.accesskey"

  39. var="userNameAccessKey" />

  40. <form:input onblur="refreshOrgList();" id="username"

  41. tabindex="1" accesskey="${userNameAccessKey}" path="username"/>

  42. </c:if>

  43. </td>

  44. </tr>

  45. <tr>

  46. <td class="label">密码:</td>

  47. <td><form:password cssClass="required" cssErrorClass="error"

  48. id="password" size="25" tabindex="2" path="password"

  49. accesskey="${passwordAccessKey}" autocomplete="off" />

  50. </td>

  51. </tr>

  52.  
  53. <tr>

  54. <td class="label">公司ID:</td>

  55. <td>

  56. <select id="companyid" name="companyid" >

  57. <option value="101" selected>上海煤气公司</option>

  58. <option value="102" selected>上海自来水厂</option>

  59. <option value="103" selected>FBI</option>

  60. <option value="104" selected>神盾局</option>

  61. </select>

  62. </td>

  63. </tr>

  64. <tr>

  65. <td class="label"></td>

  66. <td><font color="red"><form:errors id="msg" class="errors" /> </font></td>

  67. </tr>

  68. </table>

  69. </div>

  70. <div class="but_div">

  71. <input type="hidden" name="lt" value="${loginTicket}" />

  72. <input type="hidden" name="execution" value="${flowExecutionKey}" />

  73. <input type="hidden" name="_eventId" value="submit" />

  74. <input name="submit" accesskey="l" class="login_but" value="<spring:message code="screen.welcome.button.login" />"

  75. tabindex="4" type="submit" />

  76. <input name="button2" type="reset" class="cancel_but" id="button2" value="取 消" />

  77.  
  78. </div>

  79. </form:form>

  80. <div class="loginbottom_div">

  81. <div>Copyright  &copy; 红肠啃僵尸 reserved.</div>

  82. </div>

  83. </body>

 

你可以直接使用我做的页面,我把它也上传在”资源共享”中了,你也可以自己照着我这个jsp动手去改,改前请一定记得保存好原文件,反正改坏了你就再改一遍,改个4,5次也就习惯了,呵呵!

 

修改src/main/webapp/WEB-INF/view/jsp/default/protocol/2.0/casServiceValidationSuccess.jsp

CAS SSO中这个jsp是用于在用户登录成功后把用户登录成功后的信息组成一个map传给客户端调用的,即客户端可以通过如下代码:

 
  1. Map attributes = principal.getAttributes();

  2. String email = (String) attributes.get("email");

 

它是通过CAS SSO服务端的attributeDao来取得相关的LDAP中的其余信息的,但是它默认只带username到客户端 ,因此为了让客户端能够取得以下这些额外的信息:

 
  1. <property name="resultAttributeMapping">

  2. <map>

  3. <entry key="uid" value="loginid" />

  4. <entry key="mail" value="email" />

  5. </map>

  6. </property>

 

我们需要更改这个jsp代码,打开该JSP,加入如下的这段代码:

 
  1. <!-- return more attributes from attributeRepository start -->

  2. <c:if test="${fn:length(assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.attributes) > 0}">

  3.  
  4. <cas:attributes>

  5.  
  6. <c:forEach var="attr" items="${assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.attributes}">

  7.  
  8. <cas:${fn:escapeXml(attr.key)}>${fn:escapeXml(attr.value)}</cas:${fn:escapeXml(attr.key)}>

  9.  
  10. </c:forEach>

  11.  
  12. </cas:attributes>

  13.  
  14. </c:if>

  15. <!-- return more attributes from attributeRepository end -->


改完后的casServiceValidationSuccess.jsp完整代码如下,请注意<!-- return more attributes from attributeRepository start --><!-- return more attributes from attributeRepository end-->处的代码,这段代码就是我们新增的用于向客户端返回attributeDao中取出的所有的属性的遍历代码:

 

 
  1. <%@ page session="false" %>

  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

  3. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

  4. <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>

  5. <cas:authenticationSuccess>

  6. <cas:user>${fn:escapeXml(assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.id)}

  7. </cas:user>

  8.  
  9. <!-- return more attributes from attributeRepository start -->

  10. <c:if test="${fn:length(assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.attributes) > 0}">

  11.  
  12. <cas:attributes>

  13.  
  14. <c:forEach var="attr" items="${assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.attributes}">

  15.  
  16. <cas:${fn:escapeXml(attr.key)}>${fn:escapeXml(attr.value)}</cas:${fn:escapeXml(attr.key)}>

  17.  
  18. </c:forEach>

  19.  
  20. </cas:attributes>

  21.  
  22. </c:if>

  23. <!-- return more attributes from attributeRepository end -->

  24.  
  25. <c:if test="${not empty pgtIou}">

  26. <cas:proxyGrantingTicket>${pgtIou}</cas:proxyGrantingTicket>

  27. </c:if>

  28. <c:if test="${fn:length(assertion.chainedAuthentications) > 1}">

  29. <cas:proxies>

  30. <c:forEach var="proxy" items="${assertion.chainedAuthentications}" varStatus="loopStatus" begin="0" end="${fn:length(assertion.chainedAuthentications)-2}" step="1">

  31. <cas:proxy>${fn:escapeXml(proxy.principal.id)}</cas:proxy>

  32. </c:forEach>

  33. </cas:proxies>

  34. </c:if>

  35. </cas:authenticationSuccess>

  36. </cas:serviceResponse>

 

好了,终于全改完了,开始书写我们的客户端来做这个测试吧。

 

制作测试用客户端工程

在客户端我们会设置一个web session,把从cas-server带过来的用户ID,租户ID以及存在LDAP中的该客户的email都存储于这个session中。

 

为此,我们需要这样一个东西:即我们需要一个filter,用于在每次从CAS SSO登录成功后转到客户端时把相关的用户登录信息存储到web session中去。

 

当然,这些工作涉及到一系列的工具类,而且这些个工具类对于cas-sample-site1和cas-sample-site2具有同样的功能,出于代码可维护性以及统一性的考虑,这两个工程所使用到的这块代码功能都是相同的,因此我们来重组一下我们的客户端工程的目录结构吧。

 

 

myplatform工程

myplatform工程结构

该工程是cas-sample-site1和cas-sample-site2共用的一个工程,它的结构如下:

 

myplatform工程与CAS客户端工程cas-sample-site1和cas-sample-site2的依赖关系

 

两个客户端工程的依赖全部如上面图示所列那样去设置

 

存储客户登录信息的UserSession

 
  1. package org.sky.framework.session;

  2.  
  3. import java.io.Serializable;

  4.  
  5. public class UserSession implements Serializable {

  6.  
  7. private String companyId = "";

  8. private String userName = "";

  9. private String userEmail = "";

  10.  
  11. public String getCompanyId() {

  12. return companyId;

  13. }

  14.  
  15. public void setCompanyId(String companyId) {

  16. this.companyId = companyId;

  17. }

  18.  
  19. public String getUserName() {

  20. return userName;

  21. }

  22.  
  23. public void setUserName(String userName) {

  24. this.userName = userName;

  25. }

  26.  
  27. public String getUserEmail() {

  28. return userEmail;

  29. }

  30.  
  31. public void setUserEmail(String userEmail) {

  32. this.userEmail = userEmail;

  33. }

  34.  
  35. }

 

AppSessionListener

 
  1. package org.sky.framework.session;

  2.  
  3. import javax.servlet.http.HttpSessionEvent;

  4. import javax.servlet.http.HttpSessionListener;

  5. import org.slf4j.Logger;

  6. import org.slf4j.LoggerFactory;

  7. import javax.servlet.ServletContext;

  8. import javax.servlet.ServletRequestEvent;

  9. import javax.servlet.ServletRequestListener;

  10. import javax.servlet.http.HttpServletRequest;

  11. import javax.servlet.http.HttpSession;

  12.  
  13. public class AppSessionListener implements HttpSessionListener {

  14.  
  15. protected Logger logger = LoggerFactory.getLogger(this.getClass());

  16.  
  17. @Override

  18. public void sessionCreated(HttpSessionEvent se) {

  19. HttpSession session = null;

  20. try {

  21. session = se.getSession();

  22. // get value

  23. ServletContext context = session.getServletContext();

  24. String timeoutValue = context.getInitParameter("sessionTimeout");

  25. int timeout = Integer.valueOf(timeoutValue);

  26. // set value

  27. session.setMaxInactiveInterval(timeout);

  28. logger.info(">>>>>>session max inactive interval has been set to "

  29. + timeout + " seconds.");

  30. } catch (Exception ex) {

  31. ex.printStackTrace();

  32. }

  33.  
  34. }

  35.  
  36. @Override

  37. public void sessionDestroyed(HttpSessionEvent arg0) {

  38. // TODO Auto-generated method stub

  39.  
  40. }

  41.  
  42. }

 

我们的filter SampleSSOSessionFilter

 
  1. package org.sky.framework.session;

  2.  
  3. import javax.servlet.Filter;

  4. import javax.servlet.FilterChain;

  5. import javax.servlet.FilterConfig;

  6. import javax.servlet.RequestDispatcher;

  7. import javax.servlet.ServletContext;

  8. import javax.servlet.ServletException;

  9. import javax.servlet.ServletRequest;

  10. import javax.servlet.ServletResponse;

  11. import javax.servlet.http.HttpServletRequest;

  12. import javax.servlet.http.HttpServletResponse;

  13. import javax.servlet.http.HttpSession;

  14. import java.io.IOException;

  15. import java.io.PrintWriter;

  16. import java.util.Enumeration;

  17. import java.util.HashMap;

  18. import java.util.Map;

  19.  
  20. import org.jasig.cas.client.authentication.AttributePrincipal;

  21. import org.jasig.cas.client.util.AssertionHolder;

  22. import org.jasig.cas.client.validation.Assertion;

  23. import org.sky.util.WebConstants;

  24. import org.slf4j.Logger;

  25. import org.slf4j.LoggerFactory;

  26.  
  27. public class SampleSSOSessionFilter implements Filter {

  28. protected Logger logger = LoggerFactory.getLogger(this.getClass());

  29. private String excluded;

  30. private static final String EXCLUDE = "exclude";

  31. private boolean no_init = true;

  32. private ServletContext context = null;

  33. private FilterConfig config;

  34. String url = "";

  35. String actionName = "";

  36.  
  37. public void setFilterConfig(FilterConfig paramFilterConfig) {

  38. if (this.no_init) {

  39. this.no_init = false;

  40. this.config = paramFilterConfig;

  41. if ((this.excluded = paramFilterConfig.getInitParameter("exclude")) != null)

  42. this.excluded += ",";

  43. }

  44. }

  45.  
  46. private String getActionName(String actionPath) {

  47. logger.debug("filter actionPath====" + actionPath);

  48. StringBuffer actionName = new StringBuffer();

  49. try {

  50. int begin = actionPath.lastIndexOf("/");

  51. if (begin >= 0) {

  52. actionName.append(actionPath.substring(begin, actionPath.length()));

  53. }

  54. } catch (Exception e) {

  55. }

  56. return actionName.toString();

  57. }

  58.  
  59. private boolean excluded(String paramString) {

  60. // logger.info("paramString====" + paramString);

  61. // logger.info("excluded====" + this.excluded);

  62. // logger.info(this.excluded.indexOf(paramString + ","));

  63. if ((paramString == null) || (this.excluded == null))

  64. return false;

  65. return (this.excluded.indexOf(paramString + ",") >= 0);

  66. }

  67.  
  68. @Override

  69. public void destroy() {

  70. // TODO Auto-generated method stub

  71.  
  72. }

  73.  
  74. @Override

  75. public void doFilter(ServletRequest request, ServletResponse response, FilterChain arg2) throws IOException, ServletException {

  76. HttpServletRequest req = (HttpServletRequest) request;

  77. HttpServletResponse resp = (HttpServletResponse) response;

  78. UserSession uinfo = new UserSession();

  79. HttpSession se = req.getSession();

  80.  
  81. url = req.getRequestURI();

  82. actionName = getActionName(url);

  83. //actionName = url;

  84. logger.debug(">>>>>>>>>>>>>>>>>>>>SampleSSOSessionFilter: request actionname" + actionName);

  85. if (!excluded(actionName)) {

  86. try {

  87. uinfo = (UserSession) se.getAttribute(WebConstants.USER_SESSION_OBJECT);

  88. AttributePrincipal principal = (AttributePrincipal) req.getUserPrincipal();

  89. String userName = principal.getName();

  90. logger.info("userName: " + userName);

  91. if (userName != null && userName.length() > 0 && uinfo == null) {

  92. Map attributes = principal.getAttributes();

  93. String email = (String) attributes.get("email");

  94. uinfo = new UserSession();

  95. String[] userAttri = userName.split(",");

  96. uinfo.setUserName(userAttri[0]);

  97. uinfo.setCompanyId(userAttri[1]);

  98. uinfo.setUserEmail(email);

  99. se.setAttribute(WebConstants.USER_SESSION_OBJECT, uinfo);

  100.  
  101. }

  102. } catch (Exception e) {

  103. logger.error("SampleSSOSessionFilter error:" + e.getMessage(), e);

  104. resp.sendRedirect(req.getContextPath() + "/syserror.jsp");

  105. return;

  106. }

  107. } else {

  108. arg2.doFilter(request, response);

  109. return;

  110. }

  111. try {

  112. arg2.doFilter(request, response);

  113. return;

  114. } catch (Exception e) {

  115. logger.error("SampleSSOSessionFilter fault: " + e.getMessage(), e);

  116. }

  117. }

  118.  
  119. @Override

  120. public void init(FilterConfig config) throws ServletException {

  121. // TODO Auto-generated method stub

  122. this.config = config;

  123. if ((this.excluded = config.getInitParameter("exclude")) != null)

  124. this.excluded += ",";

  125. this.no_init = false;

  126. }

  127. }

 

case-sample-site1和cas-sample-site2中的web.xml

我们对于这两个CAS客户端工程的web.xml文件所做出的修改如下

 

  1. 将原有的9090(因为原来我们的cas-server是放在tomcat里的,当时设的端口号为9090,那是为了避免端口号和我们的jboss中的8080重复。而现在,我们可以把所有的9090改回成8080了)。
  2. 增加以下这段代码
 
  1. <filter>

  2. <filter-name>SampleSSOSessionFilter</filter-name>

  3. <filter-class>org.sky.framework.session.SampleSSOSessionFilter</filter-class>

  4. <init-param>

  5. <param-name>exclude</param-name>

  6. <param-value>/syserror.jsp

  7. </param-value>

  8. </init-param>

  9. </filter>

  10. <filter-mapping>

  11. <filter-name>SampleSSOSessionFilter</filter-name>

  12. <url-pattern>*</url-pattern>

  13. </filter-mapping>

 

看这个filter,它有一个特殊的地方,即我在标准的基于servlet2.4标准上对这个filter扩展了一个参数。

 

因为我们为两个CAS客户端工程增加了一个syserror.jsp,以用于在获取CAS SERVER端出错时进行重定向用,而这个syserror.jsp是不需要经过什么登录、什么记录websession用的,所以,它必须是被“excluded”掉的,对吧,具体它是怎么实现的,大家可以自己跟一下代码。

 

主要是注意看SampleSSOSessionFilter中以下这段代码:

 
  1. uinfo = (UserSession) se.getAttribute(WebConstants.USER_SESSION_OBJECT);

  2. AttributePrincipal principal = (AttributePrincipal) req.getUserPrincipal();

  3. String userName = principal.getName();

  4. logger.info("userName: " + userName);

  5. if (userName != null && userName.length() > 0 && uinfo == null) {

  6. Map attributes = principal.getAttributes();

  7. String email = (String) attributes.get("email");

  8. uinfo = new UserSession();

  9. String[] userAttri = userName.split(",");

  10. uinfo.setUserName(userAttri[0]);

  11. uinfo.setCompanyId(userAttri[1]);

  12. uinfo.setUserEmail(email);

  13. se.setAttribute(WebConstants.USER_SESSION_OBJECT, uinfo);

  14.  
  15. }


好了,我们现在要做的就是为cas-sample-site1/2各配上一个用于显示我们是否能够成功从cas-server端传过来登录成功后用户信息的index.jsp了。

 

cas-sample-site1/index.jsp

 
  1. <%@ page language="java" contentType="text/html; charset=utf-8"

  2. pageEncoding="utf-8"%>

  3. <%@ page import="org.sky.framework.session.UserSession, org.sky.util.WebConstants" %>

  4. <%

  5. UserSession us=(UserSession)session.getAttribute(WebConstants.USER_SESSION_OBJECT);

  6. String uname=us.getUserName();

  7. String email=us.getUserEmail();

  8. String companyId=us.getCompanyId();

  9. %>

  10. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  11. <html>

  12. <head>

  13. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

  14. <title>cas sample site1</title>

  15. </head>

  16. <body>

  17. <h1>cas sample site1 Hello: <%=uname%>(<%=email%>) u are@Company: <%=companyId%></h1>

  18. </p>

  19. <a href="http://localhost:8080/cas-sample-site2/index.jsp">cas-sample-site2</a>

  20.  
  21. </br>

  22. <a href="http://localhost:8080/cas-server/logout">退出</a>

  23. </body>

  24. </html>

cas-sample-site2/index.jsp

 
  1. <%@ page language="java" contentType="text/html; charset=utf-8"

  2. pageEncoding="utf-8"%>

  3. <%@ page import="org.sky.framework.session.UserSession, org.sky.util.WebConstants" %>

  4. <%

  5. UserSession us=(UserSession)session.getAttribute(WebConstants.USER_SESSION_OBJECT);

  6. String uname=us.getUserName();

  7. String email=us.getUserEmail();

  8. String companyId=us.getCompanyId();

  9. %>

  10. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  11. <html>

  12. <head>

  13. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

  14. <title>cas sample site2</title>

  15. </head>

  16. <body>

  17. <h1>cas sample site2 Hello: <%=uname%>(<%=email%>) u are@Company: <%=companyId%></h1>

  18. <a href="http://localhost:8080/cas-sample-site1/index.jsp">cas-sample-site1</a>

  19. </br>

  20. <a href="http://localhost:8080/cas-server/logout">退出</a>

  21. </body>

  22. </html>

 

运行今天所有的例子

测试用ldap中所有用户的ldif代码:

 

 
  1. dn: dc=sky,dc=org

  2. dc: sky

  3. objectClass: top

  4. objectClass: domain

  5.  
  6. dn: o=company,dc=sky,dc=org

  7. objectClass: organization

  8. o: company

  9.  
  10. dn: ou=members,o=company,dc=sky,dc=org

  11. objectClass: organizationalUnit

  12. ou: members

  13.  
  14. dn: cn=user1,ou=members,o=company,dc=sky,dc=org

  15. sn: user1

  16. cn: user1

  17. userPassword: aaaaaa

  18. objectClass: organizationalPerson

  19.  
  20. dn: cn=user2,ou=members,o=company,dc=sky,dc=org

  21. sn: user2

  22. cn: user2

  23. userPassword: abcdefg

  24. objectClass: organizationalPerson

  25.  
  26. dn: uid=mk,ou=members,o=company,dc=sky,dc=org

  27. objectClass: posixAccount

  28. objectClass: top

  29. objectClass: inetOrgPerson

  30. gidNumber: 0

  31. givenName: Yuan

  32. sn: MingKai

  33. displayName: YuanMingKai

  34. uid: mk

  35. homeDirectory: e:\user

  36. mail: mk.yuan@nttdata.com

  37. cn: YuanMingKai

  38. uidNumber: 13599

  39. userPassword: {SHA}96niR3fsIyEsVNejULxb6lR3/bs=

  40.  
  41. dn: o=101,o=company,dc=sky,dc=org

  42. o: 101

  43. objectClass: organization

  44.  
  45. dn: o=102,o=company,dc=sky,dc=org

  46. o: 102

  47. objectClass: organization

  48.  
  49. dn: o=103,o=company,dc=sky,dc=org

  50. o: 103

  51. objectClass: organization

  52.  
  53. dn: o=104,o=company,dc=sky,dc=org

  54. o: 104

  55. objectClass: organization

  56.  
  57. dn: uid=marious,o=101,o=company,dc=sky,dc=org

  58. objectClass: posixAccount

  59. objectClass: top

  60. objectClass: inetOrgPerson

  61. gidNumber: 0

  62. givenName: Wang

  63. sn: LiMing

  64. displayName: WangLiMing

  65. uid: marious

  66. homeDirectory: d:\

  67. cn: WangLiMing

  68. uidNumber: 47967

  69. userPassword: {SHA}96niR3fsIyEsVNejULxb6lR3/bs=

  70. mail: aaa@a.net

  71.  
  72. dn: uid=sky,o=101,o=company,dc=sky,dc=org

  73. objectClass: posixAccount

  74. objectClass: top

  75. objectClass: inetOrgPerson

  76. gidNumber: 0

  77. givenName: Yuan

  78. sn: Tao

  79. displayName: YuanTao

  80. uid: sky

  81. homeDirectory: d:\

  82. cn: YuanTao

  83. uidNumber: 26422

  84. userPassword: {SHA}96niR3fsIyEsVNejULxb6lR3/bs=

  85. mail: bbb@b.net

  86.  
  87. dn: uid=jason,o=102,o=company,dc=sky,dc=org

  88. objectClass: posixAccount

  89. objectClass: top

  90. objectClass: inetOrgPerson

  91. gidNumber: 0

  92. givenName: zhang

  93. sn: lei

  94. displayName: zhanglei

  95. uid: jason

  96. homeDirectory: d:\

  97. cn: zhanglei

  98. uidNumber: 62360

  99. userPassword: {SHA}96niR3fsIyEsVNejULxb6lR3/bs=

  100. mail: jason@abc.net

  101.  
  102. dn: uid=andy.li,o=103,o=company,dc=sky,dc=org

  103. objectClass: posixAccount

  104. objectClass: top

  105. objectClass: inetOrgPerson

  106. gidNumber: 0

  107. givenName: Li

  108. sn: Jun

  109. displayName: LiJun

  110. uid: andy.li

  111. homeDirectory: d:\

  112. cn: LiJun

  113. uidNumber: 51204

  114. userPassword: {SHA}96niR3fsIyEsVNejULxb6lR3/bs=

  115. mail: andy.li@jesus.chris

  116.  
  117. dn: uid=pitt,o=104,o=company,dc=sky,dc=org

  118. objectClass: posixAccount

  119. objectClass: top

  120. objectClass: inetOrgPerson

  121. gidNumber: 0

  122. givenName: Brad

  123. sn: Pitt

  124. displayName: Brad Pitt

  125. uid: pitt

  126. homeDirectory: d:\

  127. cn: Brad Pitt

  128. uidNumber: 64650

  129. userPassword: {SHA}96niR3fsIyEsVNejULxb6lR3/bs=

  130. mail: pitt@hollywood.com


把:

  • cas-server
  • cas-sample-site1
  • cas-sample-site2

全部在eclipse里用jboss7运行起来:

 

 

打开一个IE,输入http://localhost:8080/cas-sample-site1,出现如下界面:

 

  • 我们在用户名处输入jason
  • 密码输入aaaaaa
  • 公司ID选择成“上海自来水厂”

点击【登录】按钮,此时页面显示如下:

 

点击cas-sample-site2这个链接,页面显示如下:

 

我们看来看jason这个人在我们的ldap中的相关信息:

 

 

再来看看“上海自来水厂”的companyid是什么:

 
  1. <select id="companyid" name="companyid" >

  2. <option value="101" selected>上海煤气公司</option>

  3. <option value="102" selected>上海自来水厂</option>

  4. <option value="103" selected>FBI</option>

  5. <option value="104" selected>神盾局</option>

  6. </select>

是102,说明我们的传值传对了。

 

我们现在再用debug模式来调试一下这个用例。

 

 

 

好了,结束今天的课程。

 

在今天的课程中我们完成了几件事,这几件事中尤其是对于多租户的CAS SSO的解决方案是目前网上没有的包括国外的网站和主力论坛上(或者说有人解决了没有公布出来):

 

  1. 自定义CAS SSO登录界面
  2. 在CAS SSO登录界面增加我们自定义的登录用元素
  3. 使用LDAP带出登录用户在LDAP内存储的其它更多的信息
  4. 实现了CAS SSO支持多租户登录的功能

虽然这一过程很痛苦,很变态,但是通过这样的一个案例,我们完成了一件了不起的事情,同时对于这种国外开源软件的customization我们也有了一个认识,就是欧美的一些软件,它的自定义都是通过扩展、继承、插件式的方式来实现的,这说明他们的软件在设计之初就考虑到了这些扩展。

 

那很多人就会来问,改了这么一堆东西,我怎么知道要改这些东西,要去动这些代码或者有些代码怎么写?

 

我回答这个问题的方式很简单,我把它称之为:play with it

 

因为开源的软件都提供源码的,你把源码都导入eclipse工程,想办法运行起来,这个过程可能折腾个1-2周吧,但是源码一旦跑起来了,你就可以自己去跟代码啦,然后看人家这块逻辑这块设计是怎么实现的,然后照着写或者按照人家的规范插入自己的一部分的自定义的代码,就这样一点点,一点点的你也就可以把本属于别人一个产品变成为自己的一套东西了,这个过程就叫play with it

 

做IT的一定要多play with it,要不然,你很难有自己的感性上的认识,没有了感性认识的基础,那也就谈不上什么“理性认识”和“升华”了,呵呵!

 

在我们今后的教程中,我们动手改代码或者集成其它开源产品的机会还有很多、很多。。。。。。甚至还会涉及到JDK里的一些东西,让我们一起慢慢来吧。

转载于:https://my.oschina.net/u/3264768/blog/1841998

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值