CAS SSO改造步骤(2)

  1. 设计完数据库之后就开始配置CAS server了。  
  2. 设计完数据库之后就开始配置CAS server了。

至于CAS server 和CAS client的配置方法网上有很多种配置方法大致都是可行的个别版本不一样。

笔者这里使用的CAS server是3.5版本,Client是3.1版本。

JDK 7以及Tomcat 7。

配置的过程需要耐心一点。

你需要首先了解SSO工作的基本原理才能在源码的基础上改造,比如源码里面关于spring文件的配置,关于数据库连接的接口部分等。

我们来看实际的代码吧。

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!--  
  3.   | deployerConfigContext.xml centralizes into one file some of the declarative configuration that  
  4.   | all CAS deployers will need to modify.  
  5.   |  
  6.   | This file declares some of the Spring-managed JavaBeans that make up a CAS deployment.    
  7.   | The beans declared in this file are instantiated at context initialization time by the Spring   
  8.   | ContextLoaderListener declared in web.xml.  It finds this file because this  
  9.   | file is among those declared in the context parameter "contextConfigLocation".  
  10.   |  
  11.   | By far the most common change you will need to make in this file is to change the last bean  
  12.   | declaration to replace the default SimpleTestUsernamePasswordAuthenticationHandler with  
  13.   | one implementing your approach for authenticating usernames and passwords.  
  14.   +-->  
  15. <beans xmlns="http://www.springframework.org/schema/beans"  
  16.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  17.        xmlns:p="http://www.springframework.org/schema/p"  
  18.        xmlns:sec="http://www.springframework.org/schema/security"  
  19.        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  20.        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">  
  21.   <!--  
  22.     | This bean declares our AuthenticationManager.  The CentralAuthenticationService service bean  
  23.     | declared in applicationContext.xml picks up this AuthenticationManager by reference to its id,   
  24.     | "authenticationManager".  Most deployers will be able to use the default AuthenticationManager  
  25.     | implementation and so do not need to change the class of this bean.  We include the whole  
  26.     | AuthenticationManager here in the userConfigContext.xml so that you can see the things you will  
  27.     | need to change in context.  
  28.     +-->  
  29.   <bean id="authenticationManager"  
  30.     class="org.jasig.cas.authentication.AuthenticationManagerImpl">  
  31.     <!--  
  32.       | This is the List of CredentialToPrincipalResolvers that identify what Principal is trying to authenticate.  
  33.       | The AuthenticationManagerImpl considers them in order, finding a CredentialToPrincipalResolver which   
  34.       | supports the presented credentials.  
  35.       |  
  36.       | AuthenticationManagerImpl uses these resolvers for two purposes.  First, it uses them to identify the Principal  
  37.       | attempting to authenticate to CAS /login .  In the default configuration, it is the DefaultCredentialsToPrincipalResolver  
  38.       | that fills this role.  If you are using some other kind of credentials than UsernamePasswordCredentials, you will need to replace  
  39.       | DefaultCredentialsToPrincipalResolver with a CredentialsToPrincipalResolver that supports the credentials you are  
  40.       | using.  
  41.       |  
  42.       | Second, AuthenticationManagerImpl uses these resolvers to identify a service requesting a proxy granting ticket.   
  43.       | In the default configuration, it is the HttpBasedServiceCredentialsToPrincipalResolver that serves this purpose.   
  44.       | You will need to change this list if you are identifying services by something more or other than their callback URL.  
  45.       +-->  
  46.     <property name="credentialsToPrincipalResolvers">  
  47.       <list>  
  48.         <!--  
  49.           | UsernamePasswordCredentialsToPrincipalResolver supports the UsernamePasswordCredentials that we use for /login   
  50.           | by default and produces SimplePrincipal instances conveying the username from the credentials.  
  51.           |   
  52.           | If you've changed your LoginFormAction to use credentials other than UsernamePasswordCredentials then you will also  
  53.           | need to change this bean declaration (or add additional declarations) to declare a CredentialsToPrincipalResolver that supports the  
  54.           | Credentials you are using.  
  55.           +-->  
  56.           <bean class="org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver">  
  57.             <property name="attributeRepository" ref="attributeRepository" />  
  58.           </bean>  
  59.   
  60.         <!--  
  61.           | HttpBasedServiceCredentialsToPrincipalResolver supports HttpBasedCredentials.  It supports the CAS 2.0 approach of  
  62.           | authenticating services by SSL callback, extracting the callback URL from the Credentials and representing it as a  
  63.           | SimpleService identified by that callback URL.  
  64.           |  
  65.           | If you are representing services by something more or other than an HTTPS URL whereat they are able to  
  66.           | receive a proxy callback, you will need to change this bean declaration (or add additional declarations).  
  67.           +-->  
  68.         <bean  
  69.           class="org.jasig.cas.authentication.principal.HttpBasedServiceCredentialsToPrincipalResolver" />  
  70.       </list>  
  71.     </property>  
  72.   
  73.     <!--  
  74.       | Whereas CredentialsToPrincipalResolvers identify who it is some Credentials might authenticate,   
  75.       | AuthenticationHandlers actually authenticate credentials.  Here we declare the AuthenticationHandlers that  
  76.       | authenticate the Principals that the CredentialsToPrincipalResolvers identified.  CAS will try these handlers in turn  
  77.       | until it finds one that both supports the Credentials presented and succeeds in authenticating.  
  78.       +-->  
  79.     <property name="authenticationHandlers">  
  80.       <list>  
  81.         <!--  
  82.           | This is the authentication handler that authenticates services by means of callback via SSL, thereby validating  
  83.           | a server side SSL certificate.  
  84.           +-->  
  85.         <bean class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"  
  86.           p:httpClient-ref="httpClient" />  
  87.         <!--  
  88.           | This is the authentication handler declaration that every CAS deployer will need to change before deploying CAS   
  89.           | into production.  The default SimpleTestUsernamePasswordAuthenticationHandler authenticates UsernamePasswordCredentials  
  90.           | where the username equals the password.  You will need to replace this with an AuthenticationHandler that implements your  
  91.           | local authentication strategy.  You might accomplish this by coding a new such handler and declaring  
  92.           | edu.someschool.its.cas.MySpecialHandler here, or you might use one of the handlers provided in the adaptors modules.  
  93.           +-->  
  94.         <!--<bean  
  95.           class="org.jasig.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler" />  
  96.         -->  
  97.        <!-- <bean class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">  
  98.           <property name="sql" value="select PASSWORD from GERSAUTH.USERS where EMAIL=?" />  
  99.           <property name="dataSource" ref="casDataSource" />  
  100.           <property name="passwordEncoder" ref="passwordEncoder"/>  
  101.         </bean> -->  
  102.        <span style="color:#ff0000;"> <bean class="org.jasig.cas.authentication.handler.support.AppRegisteredOrNotAuthenticationHandler"  
  103.           p:httpClient-ref="httpClient">  
  104.           <property name="queryDatabaseAuthenticationHandler" ref="queryDatabaseAuthenticationHandler"/>  
  105.           <property name="modifyLoginedStatusAttributeDAO" ref="modifyLoginedStatusAttributeDAO"/>  
  106.           <property name="applicationAuthoritiedAuthenticationDAO" ref="applicationAuthoritiedAuthenticationDAO"/>  
  107.         </bean>  
  108. </span>      </list>  
  109.     </property>  
  110.   </bean>  
  111.     
  112.   <!--  
  113.     this bean defines the user login and log out status. 
  114.   -->  
  115.   <span style="color:#006600;"><bean id="applicationAuthoritiedAuthenticationDAO" class="org.jasig.services.persondir.support.jdbc.ApplicationAuthoritiedAuthenticationDAO">  
  116.     <constructor-arg index="0" ref="casDataSource"/>  
  117.     <constructor-arg index="1">  
  118.         <value>  
  119.             SELECT COUNT(*) FROM APPLICATIONS   
  120.             WHERE APP_URL =? AND ID IN (select APP_ID FROM USER_APPS   
  121.             WHERE USER_ID = (SELECT ID FROM USERS WHERE EMAIL=?))  
  122.         </value>  
  123.     </constructor-arg>  
  124.   </bean>  
  125. </span>  <span style="color:#000099;"><bean id="modifyLoginedStatusAttributeDAO" class="org.jasig.services.persondir.support.jdbc.ModifyLoginedStatusAttributeDAO">  
  126.     <constructor-arg index="0" ref="casDataSource"/>  
  127.     <property name="updateSQL">  
  128.         <value>  
  129.             UPDATE USERS SET TOKEN=? WHERE EMAIL=?  
  130.         </value>  
  131.     </property>  
  132.     <property name="selectSQL">  
  133.         <value>  
  134.             SELECT TOKEN FROM USERS WHERE EMAIL=?  
  135.         </value>  
  136.     </property>  
  137.   </bean>  
  138. </span>    
  139.   <span style="color:#ff0000;"><bean id="queryDatabaseAuthenticationHandler" class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">  
  140.           <property name="sql" value="select PASSWORD from GERSAUTH.USERS where EMAIL=?" />  
  141.           <property name="dataSource" ref="casDataSource" />  
  142.           <!--<property name="passwordEncoder" ref="passwordEncoder"/>-->  
  143.   </bean>   
  144. </span>  <!--  
  145.   This bean defines the security roles for the Services Management application.  Simple deployments can use the in-memory version.  
  146.   More robust deployments will want to use another option, such as the Jdbc version.  
  147.     
  148.   The name of this should remain "userDetailsService" in order for Spring Security to find it.  
  149.    -->  
  150.   <!-- <sec:user name="@@THIS SHOULD BE REPLACED@@" password="notused" authorities="ROLE_ADMIN" /> 
  151.   -->  
  152.   <sec:user-service id="userDetailsService">  
  153.     <sec:user name="@@THIS SHOULD BE REPLACED@@" password="notused" authorities="ROLE_ADMIN" />  
  154.   </sec:user-service>  
  155.   
  156.   <!--   
  157.   Bean that defines the attributes that a service may return.  This example uses the Stub/Mock version.  A real implementation  
  158.   may go against a database or LDAP server.  The id should remain "attributeRepository" though.  
  159.      
  160.   <bean id="attributeRepository"  
  161.     class="org.jasig.services.persondir.support.StubPersonAttributeDao">  
  162.   <property name="backingMap">  
  163.     <map>  
  164.       <entry key="uid" value="uid" />  
  165.       <entry key="eduPersonAffiliation" value="eduPersonAffiliation" />  
  166.       <entry key="groupMembership" value="groupMembership" />  
  167.     </map>  
  168.   </property>  
  169. </bean>  
  170. -->  
  171. <!--   
  172.   Sample, in-memory data store for the ServiceRegistry. A real implementation  
  173.   would probably want to replace this with the JPA-backed ServiceRegistry DAO  
  174.   The name of this bean should remain "serviceRegistryDao".  
  175.    -->  
  176. <bean  
  177.     id="serviceRegistryDao"  
  178.         class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl" >  
  179.     <property name="registeredServices">  
  180.       <list>  
  181.         <bean class="org.jasig.cas.services.RegisteredServiceImpl">  
  182.           <property name="id" value="0" />  
  183.           <property name="name" value="HTTP" />  
  184.           <property name="description" value="Only Allows HTTP Urls" />  
  185.           <property name="serviceId" value="http://**" />  
  186.           <property name="evaluationOrder" value="10000001" />  
  187.           <!-- ignoreAttributes为true表示 配置的 resultAttributeMapping 会返回-->  
  188.          <span style="color:#ff0000;"> <property name="ignoreAttributes" value="true" />  
  189.           <property name="allowedAttributes">  
  190.             <list>  
  191.               <value>id</value>  
  192.               <value>app_name</value>  
  193.               <value>app_url</value>  
  194.             </list>  
  195.           </property>  
  196.         </bean>  
  197.   
  198. </span>        <bean class="org.jasig.cas.services.RegisteredServiceImpl">  
  199.           <property name="id" value="1" />  
  200.           <property name="name" value="HTTPS" />  
  201.           <property name="description" value="Only Allows HTTPS Urls" />  
  202.           <property name="serviceId" value="https://**" />  
  203.           <property name="evaluationOrder" value="10000002" />  
  204.           <!-- ignoreAttributes为true表示 配置的 resultAttributeMapping 会返回-->  
  205.           <property name="ignoreAttributes" value="true" />  
  206.         </bean>  
  207.   
  208.         <bean class="org.jasig.cas.services.RegisteredServiceImpl">  
  209.           <property name="id" value="2" />  
  210.           <property name="name" value="IMAPS" />  
  211.           <property name="description" value="Only Allows HTTPS Urls" />  
  212.           <property name="serviceId" value="imaps://**" />  
  213.           <property name="evaluationOrder" value="10000003" />  
  214.           <!-- ignoreAttributes为true表示 配置的 resultAttributeMapping 会返回-->  
  215.           <property name="ignoreAttributes" value="true" />  
  216.         </bean>  
  217.   
  218.         <bean class="org.jasig.cas.services.RegisteredServiceImpl">  
  219.           <property name="id" value="3" />  
  220.           <property name="name" value="IMAP" />  
  221.           <property name="description" value="Only Allows IMAP Urls" />  
  222.           <property name="serviceId" value="imap://**" />  
  223.           <property name="evaluationOrder" value="10000004" />  
  224.           <!-- ignoreAttributes为true表示 配置的 resultAttributeMapping 会返回-->  
  225.           <property name="ignoreAttributes" value="true" />  
  226.         </bean>  
  227.       </list>  
  228.     </property>  
  229. </bean>  
  230.   
  231. <bean id="auditTrailManager" class="com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager" />  
  232.   
  233. <bean id="casDataSource" class="org.apache.commons.dbcp.BasicDataSource">  
  234. <property name="driverClassName">  
  235. <value>com.ibm.db2.jcc.DB2Driver</value>  
  236. </property>  
  237. <property name="url">  
  238. <value>jdbc:db2://9.115.46.188:50001/xxxx</value>  
  239. </property>  
  240. <property name="username">  
  241. <value>xxxx</value>  
  242. </property>  
  243. <property name="password">  
  244. <value>xxxxx</value>  
  245. </property>  
  246. </bean>  
  247.   
  248. <bean id="attributeRepository" class="org.jasig.services.persondir.support.jdbc.MultiRowJdbcPersonAttributeDao">  
  249. <constructor-arg index="0" ref="casDataSource" />  
  250.   
  251. <constructor-arg index="1">  
  252. <value>  
  253.   SELECT * FROM APPLICATIONS WHERE  
  254.     ID IN( SELECT APP_ID FROM USER_APPS  
  255.         WHERE USER_ID =( SELECT ID FROM USERS WHERE {0}))  
  256. </value>  
  257. </constructor-arg>  
  258.   
  259. <property name="queryAttributeMapping">  
  260. <map>  
  261.   <entry key="username" value="EMAIL"/>  
  262. </map>  
  263. </property>  
  264. <property name="nameValueColumnMappings">  
  265. <map>  
  266.   <entry key="ID" value="id" />  
  267.   <entry key="APP_NAME" value="app_name" />  
  268.   <entry key="APP_URL" value="app_url" />  
  269. </map>  
  270. </property>  
  271. </bean>  
  272.   
  273. </beans>  
<?xml version="1.0" encoding="UTF-8"?>
<!--
  | deployerConfigContext.xml centralizes into one file some of the declarative configuration that
  | all CAS deployers will need to modify.
  |
  | This file declares some of the Spring-managed JavaBeans that make up a CAS deployment.  
  | The beans declared in this file are instantiated at context initialization time by the Spring 
  | ContextLoaderListener declared in web.xml.  It finds this file because this
  | file is among those declared in the context parameter "contextConfigLocation".
  |
  | By far the most common change you will need to make in this file is to change the last bean
  | declaration to replace the default SimpleTestUsernamePasswordAuthenticationHandler with
  | one implementing your approach for authenticating usernames and passwords.
  +-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:sec="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
  <!--
    | This bean declares our AuthenticationManager.  The CentralAuthenticationService service bean
    | declared in applicationContext.xml picks up this AuthenticationManager by reference to its id, 
    | "authenticationManager".  Most deployers will be able to use the default AuthenticationManager
    | implementation and so do not need to change the class of this bean.  We include the whole
    | AuthenticationManager here in the userConfigContext.xml so that you can see the things you will
    | need to change in context.
    +-->
  <bean id="authenticationManager"
    class="org.jasig.cas.authentication.AuthenticationManagerImpl">
    <!--
      | This is the List of CredentialToPrincipalResolvers that identify what Principal is trying to authenticate.
      | The AuthenticationManagerImpl considers them in order, finding a CredentialToPrincipalResolver which 
      | supports the presented credentials.
      |
      | AuthenticationManagerImpl uses these resolvers for two purposes.  First, it uses them to identify the Principal
      | attempting to authenticate to CAS /login .  In the default configuration, it is the DefaultCredentialsToPrincipalResolver
      | that fills this role.  If you are using some other kind of credentials than UsernamePasswordCredentials, you will need to replace
      | DefaultCredentialsToPrincipalResolver with a CredentialsToPrincipalResolver that supports the credentials you are
      | using.
      |
      | Second, AuthenticationManagerImpl uses these resolvers to identify a service requesting a proxy granting ticket. 
      | In the default configuration, it is the HttpBasedServiceCredentialsToPrincipalResolver that serves this purpose. 
      | You will need to change this list if you are identifying services by something more or other than their callback URL.
      +-->
    <property name="credentialsToPrincipalResolvers">
      <list>
        <!--
          | UsernamePasswordCredentialsToPrincipalResolver supports the UsernamePasswordCredentials that we use for /login 
          | by default and produces SimplePrincipal instances conveying the username from the credentials.
          | 
          | If you've changed your LoginFormAction to use credentials other than UsernamePasswordCredentials then you will also
          | need to change this bean declaration (or add additional declarations) to declare a CredentialsToPrincipalResolver that supports the
          | Credentials you are using.
          +-->
          <bean class="org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver">
            <property name="attributeRepository" ref="attributeRepository" />
          </bean>

        <!--
          | HttpBasedServiceCredentialsToPrincipalResolver supports HttpBasedCredentials.  It supports the CAS 2.0 approach of
          | authenticating services by SSL callback, extracting the callback URL from the Credentials and representing it as a
          | SimpleService identified by that callback URL.
          |
          | If you are representing services by something more or other than an HTTPS URL whereat they are able to
          | receive a proxy callback, you will need to change this bean declaration (or add additional declarations).
          +-->
        <bean
          class="org.jasig.cas.authentication.principal.HttpBasedServiceCredentialsToPrincipalResolver" />
      </list>
    </property>

    <!--
      | Whereas CredentialsToPrincipalResolvers identify who it is some Credentials might authenticate, 
      | AuthenticationHandlers actually authenticate credentials.  Here we declare the AuthenticationHandlers that
      | authenticate the Principals that the CredentialsToPrincipalResolvers identified.  CAS will try these handlers in turn
      | until it finds one that both supports the Credentials presented and succeeds in authenticating.
      +-->
    <property name="authenticationHandlers">
      <list>
        <!--
          | This is the authentication handler that authenticates services by means of callback via SSL, thereby validating
          | a server side SSL certificate.
          +-->
        <bean class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"
          p:httpClient-ref="httpClient" />
        <!--
          | This is the authentication handler declaration that every CAS deployer will need to change before deploying CAS 
          | into production.  The default SimpleTestUsernamePasswordAuthenticationHandler authenticates UsernamePasswordCredentials
          | where the username equals the password.  You will need to replace this with an AuthenticationHandler that implements your
          | local authentication strategy.  You might accomplish this by coding a new such handler and declaring
          | edu.someschool.its.cas.MySpecialHandler here, or you might use one of the handlers provided in the adaptors modules.
          +-->
        <!--<bean
          class="org.jasig.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler" />
        -->
       <!-- <bean class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">
          <property name="sql" value="select PASSWORD from GERSAUTH.USERS where EMAIL=?" />
          <property name="dataSource" ref="casDataSource" />
          <property name="passwordEncoder" ref="passwordEncoder"/>
        </bean> -->
        <bean class="org.jasig.cas.authentication.handler.support.AppRegisteredOrNotAuthenticationHandler"
          p:httpClient-ref="httpClient">
          <property name="queryDatabaseAuthenticationHandler" ref="queryDatabaseAuthenticationHandler"/>
          <property name="modifyLoginedStatusAttributeDAO" ref="modifyLoginedStatusAttributeDAO"/>
          <property name="applicationAuthoritiedAuthenticationDAO" ref="applicationAuthoritiedAuthenticationDAO"/>
        </bean>
      </list>
    </property>
  </bean>
  
  <!-- 
  	this bean defines the user login and log out status.
  -->
  <bean id="applicationAuthoritiedAuthenticationDAO" class="org.jasig.services.persondir.support.jdbc.ApplicationAuthoritiedAuthenticationDAO">
  	<constructor-arg index="0" ref="casDataSource"/>
  	<constructor-arg index="1">
  		<value>
  			SELECT COUNT(*) FROM APPLICATIONS 
  			WHERE APP_URL =? AND ID IN (select APP_ID FROM USER_APPS 
  			WHERE USER_ID = (SELECT ID FROM USERS WHERE EMAIL=?))
  		</value>
  	</constructor-arg>
  </bean>
  <bean id="modifyLoginedStatusAttributeDAO" class="org.jasig.services.persondir.support.jdbc.ModifyLoginedStatusAttributeDAO">
  	<constructor-arg index="0" ref="casDataSource"/>
  	<property name="updateSQL">
  		<value>
  			UPDATE USERS SET TOKEN=? WHERE EMAIL=?
  		</value>
  	</property>
  	<property name="selectSQL">
  		<value>
  			SELECT TOKEN FROM USERS WHERE EMAIL=?
  		</value>
  	</property>
  </bean>
  
  <bean id="queryDatabaseAuthenticationHandler" class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">
          <property name="sql" value="select PASSWORD from GERSAUTH.USERS where EMAIL=?" />
          <property name="dataSource" ref="casDataSource" />
          <!--<property name="passwordEncoder" ref="passwordEncoder"/>-->
  </bean> 
  <!--
  This bean defines the security roles for the Services Management application.  Simple deployments can use the in-memory version.
  More robust deployments will want to use another option, such as the Jdbc version.
  
  The name of this should remain "userDetailsService" in order for Spring Security to find it.
   -->
  <!-- <sec:user name="@@THIS SHOULD BE REPLACED@@" password="notused" authorities="ROLE_ADMIN" />
  -->
  <sec:user-service id="userDetailsService">
    <sec:user name="@@THIS SHOULD BE REPLACED@@" password="notused" authorities="ROLE_ADMIN" />
  </sec:user-service>

  <!-- 
  Bean that defines the attributes that a service may return.  This example uses the Stub/Mock version.  A real implementation
  may go against a database or LDAP server.  The id should remain "attributeRepository" though.
   
  <bean id="attributeRepository"
    class="org.jasig.services.persondir.support.StubPersonAttributeDao">
  <property name="backingMap">
    <map>
      <entry key="uid" value="uid" />
      <entry key="eduPersonAffiliation" value="eduPersonAffiliation" />
      <entry key="groupMembership" value="groupMembership" />
    </map>
  </property>
</bean>
-->
<!-- 
  Sample, in-memory data store for the ServiceRegistry. A real implementation
  would probably want to replace this with the JPA-backed ServiceRegistry DAO
  The name of this bean should remain "serviceRegistryDao".
   -->
<bean
    id="serviceRegistryDao"
        class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl" >
    <property name="registeredServices">
      <list>
        <bean class="org.jasig.cas.services.RegisteredServiceImpl">
          <property name="id" value="0" />
          <property name="name" value="HTTP" />
          <property name="description" value="Only Allows HTTP Urls" />
          <property name="serviceId" value="http://**" />
          <property name="evaluationOrder" value="10000001" />
          <!-- ignoreAttributes为true表示 配置的 resultAttributeMapping 会返回-->
          <property name="ignoreAttributes" value="true" />
          <property name="allowedAttributes">
            <list>
              <value>id</value>
              <value>app_name</value>
              <value>app_url</value>
            </list>
          </property>
        </bean>

        <bean class="org.jasig.cas.services.RegisteredServiceImpl">
          <property name="id" value="1" />
          <property name="name" value="HTTPS" />
          <property name="description" value="Only Allows HTTPS Urls" />
          <property name="serviceId" value="https://**" />
          <property name="evaluationOrder" value="10000002" />
          <!-- ignoreAttributes为true表示 配置的 resultAttributeMapping 会返回-->
          <property name="ignoreAttributes" value="true" />
        </bean>

        <bean class="org.jasig.cas.services.RegisteredServiceImpl">
          <property name="id" value="2" />
          <property name="name" value="IMAPS" />
          <property name="description" value="Only Allows HTTPS Urls" />
          <property name="serviceId" value="imaps://**" />
          <property name="evaluationOrder" value="10000003" />
          <!-- ignoreAttributes为true表示 配置的 resultAttributeMapping 会返回-->
          <property name="ignoreAttributes" value="true" />
        </bean>

        <bean class="org.jasig.cas.services.RegisteredServiceImpl">
          <property name="id" value="3" />
          <property name="name" value="IMAP" />
          <property name="description" value="Only Allows IMAP Urls" />
          <property name="serviceId" value="imap://**" />
          <property name="evaluationOrder" value="10000004" />
          <!-- ignoreAttributes为true表示 配置的 resultAttributeMapping 会返回-->
          <property name="ignoreAttributes" value="true" />
        </bean>
      </list>
    </property>
</bean>

<bean id="auditTrailManager" class="com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager" />

<bean id="casDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>com.ibm.db2.jcc.DB2Driver</value>
</property>
<property name="url">
<value>jdbc:db2://9.115.46.188:50001/xxxx</value>
</property>
<property name="username">
<value>xxxx</value>
</property>
<property name="password">
<value>xxxxx</value>
</property>
</bean>

<bean id="attributeRepository" class="org.jasig.services.persondir.support.jdbc.MultiRowJdbcPersonAttributeDao">
<constructor-arg index="0" ref="casDataSource" />

<constructor-arg index="1">
<value>
  SELECT * FROM APPLICATIONS WHERE
    ID IN( SELECT APP_ID FROM USER_APPS
        WHERE USER_ID =( SELECT ID FROM USERS WHERE {0}))
</value>
</constructor-arg>

<property name="queryAttributeMapping">
<map>
  <entry key="username" value="EMAIL"/>
</map>
</property>
<property name="nameValueColumnMappings">
<map>
  <entry key="ID" value="id" />
  <entry key="APP_NAME" value="app_name" />
  <entry key="APP_URL" value="app_url" />
</map>
</property>
</bean>

</beans>

为deployerConfigContext.xml文件的更改内容。

红色部分为登录的时候验证用户名和密码以及用户是否登录,用户是否有访问该应用的权限等。

这里我们先看改动的地方。这里我新建了一个集成类然后将系统自带的QueryDatabaseAuthenticationHandler作为新建类AppRegisteredOrNotAuthenticationHandler的引用。

AppRegisteredOrNotAuthenticationHandler类的内容为:

 

  1. public final class AppRegisteredOrNotAuthenticationHandler implements  
  2.         AuthenticationHandler {  
  3.   
  4.     /** The string representing the HTTPS protocol. */  
  5.     private static final String PROTOCOL_HTTPS = "https";  
  6.     /** Log instance. */  
  7.     private final Logger log = LoggerFactory.getLogger(getClass());  
  8.     <span style="color:#3333ff;">private HttpServletRequest httpServletRequest;  
  9. </span> /** Instance of Apache Commons HttpClient */  
  10.   
  11.     /** Boolean variable denoting whether secure connection is required or not. */  
  12.     private boolean requireSecure = true;  
  13.   
  14.     <span style="color:#000099;BACKGROUND-COLOR: #ffffff">@NotNull  
  15.     private ModifyLoginedStatusAttributeDAO modifyLoginedStatusAttributeDAO;  
  16.   
  17.     @NotNull  
  18.     private ApplicationAuthoritiedAuthenticationDAO applicationAuthoritiedAuthenticationDAO;  
  19. </span> /** Instance of Apache Commons HttpClient */  
  20.     <span style="color:#000099;">@NotNull  
  21.     private HttpClient httpClient;  
  22.   
  23.     private QueryDatabaseAuthenticationHandler queryDatabaseAuthenticationHandler;  
  24.   
  25. </span> /** 
  26.      * authentication username and password. everytime check whether user has 
  27.      * logged in other place update login status ,change token =1, then 
  28.      * authenticate the url requested is valid or not. 
  29.      * */  
  30.     <span style="color:#ff0000;">public boolean authenticate(final Credentials credentials) {  
  31.         final UsernamePasswordCredentials userinfo = (UsernamePasswordCredentials) credentials;  
  32.         try {  
  33.             boolean userinfoAuth = this.getQueryDatabaseAuthenticationHandler()  
  34.                     .authenticate(userinfo);  
  35.             if (!userinfoAuth) {  
  36.                 return false;  
  37.             }  
  38.         } catch (AuthenticationException e) {  
  39.             // TODO Auto-generated catch block  
  40.             log.error("Authentication username and password Database wrong!");  
  41.         }  
  42.         try {  
  43.             boolean status = this.modifyLoginedStatusAttributeDAO  
  44.                     .CheckLogged(userinfo.getUsername());  
  45.             if (status) {  
  46.                 return false;  
  47.             }  
  48.             String url = this.httpServletRequest.getParameter("service");  
  49.             // get the main domain and port from url  
  50.             boolean result = this.applicationAuthoritiedAuthenticationDAO  
  51.                     .CheckApplicationURLIsAuthority(url, userinfo.getUsername());  
  52.             if (result) {  
  53.                 log.debug("this Application not exist!");  
  54.                 return false;  
  55.             }  
  56.             // change token state  
  57.             this.modifyLoginedStatusAttributeDAO.updateToken(  
  58.                     userinfo.getUsername(), "1");  
  59.   
  60.         } catch (Exception e) {  
  61.             log.error("update token error");  
  62.         }  
  63.         return true;  
  64.     }  
  65.   
  66. </span> /** 
  67.      * @return true if the credentials provided are not null and the credentials 
  68.      *         are a subclass of (or equal to) HttpBasedServiceCredentials. 
  69.      */  
  70.     public boolean supports(final Credentials credentials) {  
  71.         return credentials != null;  
  72.     }  
  73.   
  74.     public void setQueryDatabaseAuthenticationHandler(  
  75.             QueryDatabaseAuthenticationHandler queryDatabaseAuthenticationhandler) {  
  76.         this.queryDatabaseAuthenticationHandler = queryDatabaseAuthenticationhandler;  
  77.     }  
  78.   
  79.     public QueryDatabaseAuthenticationHandler getQueryDatabaseAuthenticationHandler() {  
  80.         return queryDatabaseAuthenticationHandler;  
  81.     }  
  82.   
  83.     /** Sets the HttpClient which will do all of the connection stuff. */  
  84.     public void setHttpClient(final HttpClient httpClient) {  
  85.         this.httpClient = httpClient;  
  86.     }  
  87.   
  88.     /** 
  89.      * Set whether a secure url is required or not. 
  90.      *  
  91.      * @param requireSecure 
  92.      *            true if its required, false if not. Default is true. 
  93.      */  
  94.     public void setRequireSecure(final boolean requireSecure) {  
  95.         this.requireSecure = requireSecure;  
  96.     }  
  97.   
  98.     @Override  
  99.     public void setHttpServletRequest(HttpServletRequest request) {  
  100.         // TODO Auto-generated method stub  
  101.         this.httpServletRequest = request;  
  102.     }  
  103.   
  104.     public void setModifyLoginedStatusAttributeDAO(  
  105.             ModifyLoginedStatusAttributeDAO modifyLoginedStatusAttributeDAO) {  
  106.         this.modifyLoginedStatusAttributeDAO = modifyLoginedStatusAttributeDAO;  
  107.     }  
  108.   
  109.     public ModifyLoginedStatusAttributeDAO getModifyLoginedStatusAttributeDAO() {  
  110.         return modifyLoginedStatusAttributeDAO;  
  111.     }  
  112.   
  113.     public void setApplicationAuthoritiedAuthenticationDAO(  
  114.             ApplicationAuthoritiedAuthenticationDAO applicationAuthoritiedAuthenticationDAO) {  
  115.         this.applicationAuthoritiedAuthenticationDAO = applicationAuthoritiedAuthenticationDAO;  
  116.     }  
  117.   
  118.     public ApplicationAuthoritiedAuthenticationDAO getApplicationAuthoritiedAuthenticationDAO() {  
  119.         return applicationAuthoritiedAuthenticationDAO;  
  120.     }  
  121.   
  122. }  
public final class AppRegisteredOrNotAuthenticationHandler implements
		AuthenticationHandler {

	/** The string representing the HTTPS protocol. */
	private static final String PROTOCOL_HTTPS = "https";
	/** Log instance. */
	private final Logger log = LoggerFactory.getLogger(getClass());
	private HttpServletRequest httpServletRequest;
	/** Instance of Apache Commons HttpClient */

	/** Boolean variable denoting whether secure connection is required or not. */
	private boolean requireSecure = true;

	@NotNull
	private ModifyLoginedStatusAttributeDAO modifyLoginedStatusAttributeDAO;

	@NotNull
	private ApplicationAuthoritiedAuthenticationDAO applicationAuthoritiedAuthenticationDAO;
	/** Instance of Apache Commons HttpClient */
	@NotNull
	private HttpClient httpClient;

	private QueryDatabaseAuthenticationHandler queryDatabaseAuthenticationHandler;

	/**
	 * authentication username and password. everytime check whether user has
	 * logged in other place update login status ,change token =1, then
	 * authenticate the url requested is valid or not.
	 * */
	public boolean authenticate(final Credentials credentials) {
		final UsernamePasswordCredentials userinfo = (UsernamePasswordCredentials) credentials;
		try {
			boolean userinfoAuth = this.getQueryDatabaseAuthenticationHandler()
					.authenticate(userinfo);
			if (!userinfoAuth) {
				return false;
			}
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			log.error("Authentication username and password Database wrong!");
		}
		try {
			boolean status = this.modifyLoginedStatusAttributeDAO
					.CheckLogged(userinfo.getUsername());
			if (status) {
				return false;
			}
			String url = this.httpServletRequest.getParameter("service");
			// get the main domain and port from url
			boolean result = this.applicationAuthoritiedAuthenticationDAO
					.CheckApplicationURLIsAuthority(url, userinfo.getUsername());
			if (result) {
				log.debug("this Application not exist!");
				return false;
			}
			// change token state
			this.modifyLoginedStatusAttributeDAO.updateToken(
					userinfo.getUsername(), "1");

		} catch (Exception e) {
			log.error("update token error");
		}
		return true;
	}

	/**
	 * @return true if the credentials provided are not null and the credentials
	 *         are a subclass of (or equal to) HttpBasedServiceCredentials.
	 */
	public boolean supports(final Credentials credentials) {
		return credentials != null;
	}

	public void setQueryDatabaseAuthenticationHandler(
			QueryDatabaseAuthenticationHandler queryDatabaseAuthenticationhandler) {
		this.queryDatabaseAuthenticationHandler = queryDatabaseAuthenticationhandler;
	}

	public QueryDatabaseAuthenticationHandler getQueryDatabaseAuthenticationHandler() {
		return queryDatabaseAuthenticationHandler;
	}

	/** Sets the HttpClient which will do all of the connection stuff. */
	public void setHttpClient(final HttpClient httpClient) {
		this.httpClient = httpClient;
	}

	/**
	 * Set whether a secure url is required or not.
	 * 
	 * @param requireSecure
	 *            true if its required, false if not. Default is true.
	 */
	public void setRequireSecure(final boolean requireSecure) {
		this.requireSecure = requireSecure;
	}

	@Override
	public void setHttpServletRequest(HttpServletRequest request) {
		// TODO Auto-generated method stub
		this.httpServletRequest = request;
	}

	public void setModifyLoginedStatusAttributeDAO(
			ModifyLoginedStatusAttributeDAO modifyLoginedStatusAttributeDAO) {
		this.modifyLoginedStatusAttributeDAO = modifyLoginedStatusAttributeDAO;
	}

	public ModifyLoginedStatusAttributeDAO getModifyLoginedStatusAttributeDAO() {
		return modifyLoginedStatusAttributeDAO;
	}

	public void setApplicationAuthoritiedAuthenticationDAO(
			ApplicationAuthoritiedAuthenticationDAO applicationAuthoritiedAuthenticationDAO) {
		this.applicationAuthoritiedAuthenticationDAO = applicationAuthoritiedAuthenticationDAO;
	}

	public ApplicationAuthoritiedAuthenticationDAO getApplicationAuthoritiedAuthenticationDAO() {
		return applicationAuthoritiedAuthenticationDAO;
	}

}

代码中蓝色的几个私有变量第一个是HttpServletRequest是从认证中心传进来的变量,主要是获取Service URL添加的。

其他三个都是与数据库操作有关的。

红色部分逻辑是:首先验证用户名密码是否合法,然后再验证该用户是否已经登录,再验证用户访问的APP是否是授权的,最后如果都正确那么将登录状态更改为1;

其他几个修改的类如下:

ModifyLoginedStatusAttributeDAO.Java

  1. package org.jasig.services.persondir.support.jdbc;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import javax.sql.DataSource;  
  8.   
  9. import org.apache.commons.lang.Validate;  
  10. import org.slf4j.Logger;  
  11. import org.slf4j.LoggerFactory;  
  12. import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;  
  13. import org.springframework.util.Assert;  
  14.   
  15.   
  16. public class ModifyLoginedStatusAttributeDAO   {  
  17.   
  18.      private final Logger log = LoggerFactory.getLogger(this.getClass());  
  19.      /** set data source*/  
  20.      private final DataSource dataSource;  
  21.      private final SimpleJdbcTemplate jdbcTemplate;  
  22.      /** set update format */  
  23.      private String updateSQL;  
  24.      /** set select sql format. */  
  25.      private String selectSQL;  
  26.        
  27.      public ModifyLoginedStatusAttributeDAO(DataSource dataSource){  
  28.          Assert.notNull(dataSource,"dataSource should be initinal");  
  29.          this.dataSource = dataSource;  
  30.          this.jdbcTemplate = new SimpleJdbcTemplate(this.dataSource);  
  31.      }  
  32.      /** this method change logged status when user log in or log out. */  
  33.      public void updateToken(String username,String value){  
  34.          Assert.notNull(username, "username cannot be null");  
  35.          Assert.notNull(value,"update value cannot be null");  
  36.            
  37.          Object[] obj = {value,username};  
  38.          try{  
  39.             <span style="color:#ff0000;"this.jdbcTemplate.update(this.updateSQL, obj);  
  40. </span>      }catch(Exception e){  
  41.              log.error("update token error.");  
  42.          }  
  43.      }  
  44.      /** this method complete authenticating the user is logged in one place.*/  
  45.     public boolean CheckLogged(String username){  
  46.         Validate.notNull(username, "username should not be null");  
  47.         String result=null;  
  48.         try{  
  49.              <span style="color:#ff0000;">result = this.jdbcTemplate.queryForObject(this.selectSQL, String.class, username);  
  50. </span>     }catch(Exception e){  
  51.             log.error("select database error!");  
  52.         }  
  53.         <span style="color:#ff6600;">if(result.equals("1")){  
  54.             return true;  
  55.         }  
  56. </span>     return false;  
  57.     }  
  58.     public void setUpdateSQL(String updateSQL) {  
  59.         this.updateSQL = updateSQL;  
  60.     }  
  61.     public void setSelectSQL(String selectSQL) {  
  62.         this.selectSQL = selectSQL;  
  63.     }  
  64.   
  65. }  
package org.jasig.services.persondir.support.jdbc;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.util.Assert;


public class ModifyLoginedStatusAttributeDAO   {

	 private final Logger log = LoggerFactory.getLogger(this.getClass());
	 /** set data source*/
	 private final DataSource dataSource;
	 private final SimpleJdbcTemplate jdbcTemplate;
	 /** set update format */
	 private String updateSQL;
	 /** set select sql format. */
	 private String selectSQL;
	 
	 public ModifyLoginedStatusAttributeDAO(DataSource dataSource){
		 Assert.notNull(dataSource,"dataSource should be initinal");
		 this.dataSource = dataSource;
		 this.jdbcTemplate = new SimpleJdbcTemplate(this.dataSource);
	 }
	 /** this method change logged status when user log in or log out. */
	 public void updateToken(String username,String value){
		 Assert.notNull(username, "username cannot be null");
		 Assert.notNull(value,"update value cannot be null");
		 
		 Object[] obj = {value,username};
		 try{
			 this.jdbcTemplate.update(this.updateSQL, obj);
		 }catch(Exception e){
			 log.error("update token error.");
		 }
	 }
	 /** this method complete authenticating the user is logged in one place.*/
	public boolean CheckLogged(String username){
		Validate.notNull(username, "username should not be null");
		String result=null;
		try{
			 result = this.jdbcTemplate.queryForObject(this.selectSQL, String.class, username);
		}catch(Exception e){
			log.error("select database error!");
		}
		if(result.equals("1")){
			return true;
		}
		return false;
	}
	public void setUpdateSQL(String updateSQL) {
		this.updateSQL = updateSQL;
	}
	public void setSelectSQL(String selectSQL) {
		this.selectSQL = selectSQL;
	}

}

ApplicationAuthoritiedAuthenticationDAO.java

代码如下:

  1. <span style="color:#000000;">package org.jasig.services.persondir.support.jdbc;  
  2.   
  3. import java.util.regex.Matcher;  
  4. import java.util.regex.Pattern;  
  5.   
  6. import javax.sql.DataSource;  
  7. import javax.validation.constraints.NotNull;  
  8.   
  9. import org.apache.commons.lang.Validate;  
  10. import org.slf4j.Logger;  
  11. import org.slf4j.LoggerFactory;  
  12. import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;  
  13. import org.springframework.util.Assert;  
  14.   
  15. public class ApplicationAuthoritiedAuthenticationDAO {  
  16.     private final Logger log = LoggerFactory.getLogger(this.getClass());  
  17.     /** set data source */  
  18.     @NotNull  
  19.     private final DataSource dataSource;  
  20.     @NotNull  
  21.     private final SimpleJdbcTemplate jdbcTemplate;  
  22.   
  23.     /** set select sql format. */  
  24.     @NotNull  
  25.     private String sql;  
  26.   
  27.     public ApplicationAuthoritiedAuthenticationDAO(DataSource dataSource,  
  28.             String sql) {  
  29.         Assert.notNull(dataSource, "dataSource should be not null");  
  30.         Assert.notNull(sql, "sql statement should not be null");  
  31.         this.dataSource = dataSource;  
  32.         this.jdbcTemplate = new SimpleJdbcTemplate(this.dataSource);  
  33.         this.sql = sql;  
  34.     }  
  35.   
  36.     /** check this url is valid for this user */  
  37.     public boolean <span style="color:#ff0000;">CheckApplicationURLIsAuthority</span>(String url, String username) {  
  38.         Assert.notNull(url, "url cannot be null.");  
  39.         Assert.notNull(username, "username is null");  
  40.   
  41.         Pattern pattern = Pattern.compile("(http://|https://){1}[\\w\\.\\-:]+/[\\w]+/");   
  42.         Matcher matcher = pattern.matcher(url);   
  43.         StringBuffer buffer = new StringBuffer();   
  44.         matcher.find();              
  45.         buffer.append(matcher.group());                     
  46.         url = buffer.toString();   
  47.   
  48.         Object[] param = { url, username };  
  49.         int result = -1;  
  50.         <span style="color:#ff6600;">result = this.jdbcTemplate.queryForInt(sql, param);  
  51. </span>     if (result < 1) {  
  52.             log.debug("this Application not exist!");  
  53.             return true;  
  54.         }  
  55.         return false;  
  56.     }  
  57. }  
  58. </span>  
package org.jasig.services.persondir.support.jdbc;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.sql.DataSource;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.util.Assert;

public class ApplicationAuthoritiedAuthenticationDAO {
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	/** set data source */
	@NotNull
	private final DataSource dataSource;
	@NotNull
	private final SimpleJdbcTemplate jdbcTemplate;

	/** set select sql format. */
	@NotNull
	private String sql;

	public ApplicationAuthoritiedAuthenticationDAO(DataSource dataSource,
			String sql) {
		Assert.notNull(dataSource, "dataSource should be not null");
		Assert.notNull(sql, "sql statement should not be null");
		this.dataSource = dataSource;
		this.jdbcTemplate = new SimpleJdbcTemplate(this.dataSource);
		this.sql = sql;
	}

	/** check this url is valid for this user */
	public boolean CheckApplicationURLIsAuthority(String url, String username) {
		Assert.notNull(url, "url cannot be null.");
		Assert.notNull(username, "username is null");

		Pattern pattern = Pattern.compile("(http://|https://){1}[\\w\\.\\-:]+/[\\w]+/"); 
		Matcher matcher = pattern.matcher(url); 
		StringBuffer buffer = new StringBuffer(); 
		matcher.find();            
		buffer.append(matcher.group());                   
		url = buffer.toString(); 

		Object[] param = { url, username };
		int result = -1;
		result = this.jdbcTemplate.queryForInt(sql, param);
		if (result < 1) {
			log.debug("this Application not exist!");
			return true;
		}
		return false;
	}
}


上面是登录验证功能里面涉及到的几个类。

下一节将介绍其他部分的功能。不过其他部分的功能数据库操作部分引用以上几个类的代码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值