posts - 37,  comments - 53,  trackbacks - 0

          經(jīng)過將近兩天的測試,參考眾多網(wǎng)友的貢獻(xiàn),終于完成了對cas的主要配置和測試,現(xiàn)記錄如下

          基本需求:

          1.cas server-3.4.5,casclient-3.2(官方版本),均可在cas官方網(wǎng)站下載,http://www.jasig.org

          2.使用低成本的http協(xié)議進(jìn)行傳輸,俺買不起ssl證書

          3.通過jdbc進(jìn)行用戶驗(yàn)證

          4.需要通過casserver提供除登錄用戶名以外的附加信息

          參考資料:

          1.cas官方網(wǎng)站的用戶幫助手冊和wiki

          2.網(wǎng)友“城市獵人”的blog,http://yuzhwe.javaeye.com/blog/830143

          3.網(wǎng)友“悟空悟道”的blog,http://llhdf.javaeye.com/blog/764385

          4.其他網(wǎng)友貢獻(xiàn)的相關(guān)的blog,都是通過google出來,就不一一列出了,一并致謝?。?!

          好了,下面進(jìn)入正題,如果您不想測試中出現(xiàn)異常情況,或是獲取不到相關(guān)數(shù)據(jù),請關(guān)注文中的紅色字體部分。

          (1)使用http協(xié)議的設(shè)置,如果您也像我一樣,買不起ssl數(shù)字證書,對安全的要求也不是特別的搞,下面的配置就可以幫助解決這個問題:

          在cas-server-webapp中的/WEB-INF/spring-configuration/ticketGrantingTicketCookieGenerator.xml文件中有如下配置

          <bean id="ticketGrantingTicketCookieGenerator" class="org.jasig.cas.web.support.CookieRetrievingCookieGenerator"
            p:cookieSecure="true"     //默認(rèn)為true,使用https,如果只需要http,修改為false即可
            p:cookieMaxAge="-1"
            p:cookieName="CASTGC"
            p:cookiePath="/cas" />

           (2)使用jdbc數(shù)據(jù)源進(jìn)行用戶認(rèn)證,需要修改cas的authenticationHandlers方式,在文件/WEB-INF/deployerConfigContext.xml有如下配置:

          <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="dataSource" ref="dataSource" />
                  
          <property name="sql" value="select password from userInfo where username=? and enabled=true" />
                   //用戶密碼編碼方式

                   <property name="passwordEncoder"
                     ref="passwordEncoderBean"/>
                   </bean>  
             </list>
            </property>

          該屬性中的list只要用一個認(rèn)證通過即可,建議將紅色部分放在第一位,如果確認(rèn)只用jdbc一種方式,其他認(rèn)證方式均可刪除。另外需要在在文件中添加datasoure和passordEncoder兩個bean,如下

          <!-- Data source definition -->
           <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName">
              <value>com.mysql.jdbc.Driver</value>
            </property>
            <property name="url">
              <value>jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8</value>    //如果使用mysql數(shù)據(jù)庫,應(yīng)該加上后面的編碼參數(shù),否則可能導(dǎo)致客戶端對TGT票據(jù)無法識別的問題
            </property>
            <property name="username"><value>root</value></property>
            <property name="password"><value>password</value></property>
           </bean>
           <bean id="passwordEncoderBean" class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder">
                  <constructor-arg value="SHA1" />  //cas
          server默認(rèn)支持MD5和SHA1兩種編碼方式,如果需要其他的編碼方式例如SHA256,512等,可自行實(shí)現(xiàn)org.jasig.cas.authentication.handler.PasswordEncoder接口
              </bean>

          附加備注:如果您是使用cas server的源碼自行編譯的話,需要在cas-server-web模塊的pom.xml中添加如下模塊的依賴:

          <dependency>
                 <groupId>${project.groupId}</groupId>
                 <artifactId>cas-server-support-jdbc</artifactId>
                 <version>${project.version}</version>
            </dependency>  

          并添加對應(yīng)數(shù)據(jù)庫的jdbc的jar包。

          (3)讓cas server提供更多的用戶數(shù)據(jù)共客戶端使用

          通過測試,由于cas的代碼更新過程中的變化較大,所以包兼容的問題好像一直存在,在測試中我就碰到過,花費(fèi)時間比較多,建議同學(xué)們在使用過程中使用官方的最新的發(fā)布版本。在我使用的這個版本中,請參考前面的關(guān)于server和client端的版本說明,應(yīng)該沒有包沖突的問題,測試通過。下面進(jìn)行配置,配置文件:/WEB-INF/deployerConfigContext.xml
          <property name="credentialsToPrincipalResolvers">
             <list>
                 <!--<bean class="org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver" />-->
              <!-- modify on 2011-01-18,add user info -->
              <bean class="org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver" >
                <property name="attributeRepository" >   //為認(rèn)證過的用戶的Principal添加屬性
                <ref local="attributeRepository"/>
               </property> 
              </bean>
                <bean
               class="org.jasig.cas.authentication.principal.HttpBasedServiceCredentialsToPrincipalResolver" />
             </list>
            </property>
           修改該文件中默認(rèn)的 attributeRepositorybean配置
          <!-- 在這里配置獲取更多用戶的信息 -->
           <bean id="attributeRepository" class="org.jasig.services.persondir.support.jdbc.SingleRowJdbcPersonAttributeDao">
            <constructor-arg index="0" ref="dataSource" />
            <constructor-arg index="1" value="select id as UId, password_hint as ph from userInfo where username=? and enabled=true" />
            <property name="queryAttributeMapping">
             <map>
             <entry key="username" value="uid"/><!-- 這里必須這么寫,系統(tǒng)會自己匹配,貌似和where語句后面的用戶名字段的拼寫沒有什么關(guān)系 -->
             </map>
            </property>
             <!-- 要獲取的屬性在這里配置 -->
            <property name="resultAttributeMapping">
             <map>
             <entry key="UId" value="userId" /> //key為對應(yīng)的數(shù)據(jù)庫字段名稱,value為提供給客戶端獲取的屬性名字,系統(tǒng)會自動填充值
             <entry key="ph" value="passwordHint" />   
             </map>
            </property>
          </bean> 
          備注:網(wǎng)上有很多的關(guān)于這個的配置,但是如果您使用的是我提供的版本或是高于這個版本,就應(yīng)該象上面這樣配置,無用質(zhì)疑,網(wǎng)上大部分的配置都是基于
          person-directory-impl,person-directory-api
          1.1左右的版本,而最新的cas使用的是1.5的版本,經(jīng)過查看源代碼和api docs確定最新版本的屬性參數(shù)如上配置。

          修改該xml文件中最后一個默認(rèn)的serviceRegistryDao bean中的屬性全部注釋掉,或者刪除,
          這個bean中的RegisteredServiceImpl的ignoreAttributes屬性將決定是否添加attributes屬性內(nèi)容,默認(rèn)為false:不添加,只有去掉這個配置,
          cas server才會將獲取的用戶的附加屬性添加到認(rèn)證用的Principal的attributes中去,我在這里犯過這樣的錯誤,最后還是通過跟蹤源碼才發(fā)現(xiàn)的。
          <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://**" />
                              </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://**" />
                              </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://**" />
                              </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://**" />
                              </bean>
                          </list>
                      </property>-->
                     </bean>

           修改WEB-INF\view\jsp\protocol\2.0\casServiceValidationSuccess.jsp文件,如下:

          <%@ page session="false"%>
          <%@ taglib prefix="c" uri=">
          <%@ taglib uri="
          <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
           <cas:authenticationSuccess>
            <cas:user>${fn:escapeXml(assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.id)}</cas:user>
            <c:if test="${not empty pgtIou}">
             <cas:proxyGrantingTicket>${pgtIou}</cas:proxyGrantingTicket>
            </c:if>
            <c:if test="${fn:length(assertion.chainedAuthentications) > 1}">
             <cas:proxies>
              <c:forEach var="proxy" items="${assertion.chainedAuthentications}"
               varStatus="loopStatus" begin="0"
               end="${fn:length(assertion.chainedAuthentications)-2}" step="1">
               <cas:proxy>${fn:escapeXml(proxy.principal.id)}</cas:proxy>
              </c:forEach>
             </cas:proxies>
            </c:if>
             <c:if
             test="${fn:length(assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.attributes)

          >
          0}">
             <cas:attributes>
              <c:forEach
          var="attr"
               items="${assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.attributes}"
               varStatus="loopStatus"
          begin="0"
               end="${fn:length(assertion.chainedAuthentications[fn:length(assertion.chainedAuthentications)-1].principal.attributes)-1}"
               step="1">
               <cas:${fn:escapeXml(attr.key)}>${fn:escapeXml(attr.value)}</cas:${fn:escapeXml(attr.key)}>
              </c:forEach>
             </cas:attributes>
            </c:if>
           </cas:authenticationSuccess>
          </cas:serviceResponse>
          客戶端配置:
          1.過濾器CAS Validation Filter:
          <filter>
            <filter-name>CAS Validation Filter</filter-name>
            <filter-class> org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter</filter-class>
            <init-param>
              <param-name>casServerUrlPrefix</param-name>
              <param-value>http://domainserver:8081/cas</param-value>
            </init-param>
          </filter>
          在客戶端獲取信息
          AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
          String loginName = principal.getName();//獲取用戶名
          Map<String, Object> attributes = principal.getAttributes();
          if(attributes != null) {
           System.out.println(attributes.get("userId"));
           System.out.println(attributes.get("passwordHint"));
          }

           


           


          FeedBack:
          # re: cas配置全攻略
          2011-01-23 13:13 | 來如風(fēng)
          非常好,我上周也配置成功
          只是最后過濾器有疑問
          <init-param>
          <param-name>casServerUrlPrefix</param-name>
          <param-value>http://domainserver:8081/cas</param-value>
          </init-param>
          我是集成了spring security 的配置,貌似這些不在過濾其中配置,在bean文件中有  回復(fù)  更多評論
            
          # re: cas配置全攻略
          2011-01-24 16:29 | coolszy
          你好,按照你的配置,但是
          Map<String, Object> attributes = principal.getAttributes();
          還是得到空值,不知道什么原因  回復(fù)  更多評論
            
          # re: cas配置全攻略[未登錄]
          2011-02-07 11:02 | mcikeay
          <entry key="username" value="uid"/><!-- 這里必須這么寫,系統(tǒng)會自己匹配,貌似和where語句后面的用戶名字段的拼寫沒有什么關(guān)系 -->


          cas 會自己組裝<map>節(jié)點(diǎn)中的key-value, 節(jié)點(diǎn)間默認(rèn)是 and 連接  回復(fù)  更多評論
            
          # re: cas配置全攻略
          2011-02-14 15:15 | tufanshu
          @coolszy
          請檢查cas client的版本是否正確  回復(fù)  更多評論
            
          # re: cas配置全攻略
          2011-03-29 10:45 | wuximin
          通過ldap驗(yàn)證,改怎樣修改呢  回復(fù)  更多評論
            
          # re: cas配置全攻略
          2011-06-05 18:19 | artd
          按您的要求,為何還是不行呀,不知道那里出問題了。
          不過我用的server是3.3.5.1
          用3.4.5也不行,有空交流一下喲。
          以下是log信息
          2011-06-05 18:09:19,515 DEBUG [org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver] - Attempting to resolve a principal...
          2011-06-05 18:09:19,515 DEBUG [org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver] - Creating SimplePrincipal for [test]
          2011-06-05 18:09:20,421 DEBUG [org.jasig.services.persondir.support.jdbc.SingleRowJdbcPersonAttributeDao] - Created seed map='{username=[test]}' for uid='test'
          2011-06-05 18:09:20,421 DEBUG [org.jasig.services.persondir.support.jdbc.SingleRowJdbcPersonAttributeDao] - Adding attribute 'username' with value '[test]' to query builder 'null'
          2011-06-05 18:09:20,421 DEBUG [org.jasig.services.persondir.support.jdbc.SingleRowJdbcPersonAttributeDao] - Generated query builder 'sql=[username = ?] args=[test]' from query Map {username=[test]}.
          2011-06-05 18:09:20,546 DEBUG [org.jasig.services.persondir.support.jdbc.SingleRowJdbcPersonAttributeDao] - Executed 'select id,username,password,email,score from user where username = ?' with arguments [test] and got results [{id=20428, username=test, password=1a16128849444873, email=et@163.com, score=6}]
          2011-06-05 18:09:20,562 INFO [org.jasig.cas.CentralAuthenticationServiceImpl] - Granted service ticket [ST-1-cp3cb14yiqbqnYfg7C1f-cas] for service [http://d7.abc.com/simple.php] for user [test]
          2011-06-05 18:09:20,640 DEBUG [org.springframework.web.servlet.view.RedirectView] - Rendering view with name 'null' with model null and static attributes {}
          2011-06-05 18:09:20,703 DEBUG [org.springframework.web.servlet.view.ResourceBundleViewResolver] - Cached view [casServiceSuccessView_zh_CN]
          2011-06-05 18:09:20,703 DEBUG [org.springframework.web.servlet.view.JstlView] - Rendering view with name 'casServiceSuccessView' with model {assertion=[principals={[[Principal=test, attributes={authenticationMethod=com.jute.framework.jdbc.QueryDatabaseAuthenticationHandler}]]} for service=http://d7.abc.com/simple.php]} and static attributes {}
          2011-06-05 18:09:20,750 DEBUG [org.springframework.web.servlet.view.JstlView] - Added model object 'assertion' of type [org.jasig.cas.validation.ImmutableAssertionImpl] to request in view with name 'casServiceSuccessView'
          2011-06-05 18:09:20,750 DEBUG [org.springframework.web.servlet.view.JstlView] - Forwarding to resource [/WEB-INF/view/jsp/protocol/2.0/casServiceValidationSuccess.jsp] in InternalResourceView 'casServiceSuccessView'
            回復(fù)  更多評論
            
          # re: cas配置全攻略
          2011-10-19 15:24 | fanfree
          同樣遇到 Map是空的,沒有附加屬性  回復(fù)  更多評論
            
          # re: cas配置全攻略[未登錄]
          2013-06-17 20:06 | Jason
          lz的代碼為什么沒有用排版插件,看的不清楚啊  回復(fù)  更多評論
            
          # re: cas配置全攻略
          2015-12-16 17:46 | xxr
          可以下載你的源碼么?尤其是person-directory-api-1.5.1.jar的源碼  回復(fù)  更多評論
            
          <2015年12月>
          293012345
          6789101112
          13141516171819
          20212223242526
          272829303112
          3456789

          常用鏈接

          留言簿(17)

          隨筆分類

          隨筆檔案

          文章檔案

          blog

          搜索

          •  

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 松原市| 普兰县| 酒泉市| 桦甸市| 马龙县| 鹤庆县| 子长县| 甘孜县| 永兴县| 岳阳县| 宜昌市| 新田县| 明光市| 洮南市| 高雄县| 错那县| 泾阳县| 安丘市| 冀州市| 渭源县| 宝山区| 吴忠市| 岳西县| 台北市| 襄城县| 延安市| 陈巴尔虎旗| 土默特左旗| 龙川县| 称多县| 兰考县| 江油市| 元氏县| 紫云| 海城市| 喀喇沁旗| 七台河市| 安溪县| 龙州县| 梁山县| 专栏|