使用 CAS 在 Tomcat 中實現單點登錄(部署 CAS Server)

轉載:http://www.ibm.com/developerworks/cn/opensource/os-cn-cas/index.html

簡介: 單點登錄(Single Sign On , 簡稱 SSO )是目前比較流行的服務於企業業務整合的解決方案之一, SSO 使得在多個應用系統中,用戶只需要登錄一次就可以訪問所有相互信任的應用系統。CAS(Central Authentication Service)是一款不錯的針對 Web 應用的單點登錄框架,本文介紹了 CAS 的原理、協議、在 Tomcat 中的配置和使用,對於採用 CAS 實現輕量級單點登錄解決方案的入門讀者具有一定指導作用

 

CAS 介紹

CAS 是 Yale 大學發起的一個開源項目,旨在爲 Web 應用系統提供一種可靠的單點登錄方法,CAS 在 2004 年 12 月正式成爲 JA-SIG 的一個項目。CAS 具有以下特點:

  • 開源的企業級單點登錄解決方案。
  • CAS Server 爲需要獨立部署的 Web 應用。
  • CAS Client 支持非常多的客戶端(這裏指單點登錄系統中的各個 Web 應用),包括 Java, .Net, PHP, Perl, Apache, uPortal, Ruby 等。

CAS 原理和協議

從結構上看,CAS 包含兩個部分: CAS Server 和 CAS Client。CAS Server 需要獨立部署,主要負責對用戶的認證工作;CAS Client 負責處理對客戶端受保護資源的訪問請求,需要登錄時,重定向到 CAS Server。圖1 是 CAS 最基本的協議過程:


圖 1. CAS 基礎協議
CAS 基礎協議

CAS Client 與受保護的客戶端應用部署在一起,以 Filter 方式保護受保護的資源。對於訪問受保護資源的每個 Web 請求,CAS Client 會分析該請求的 Http 請求中是否包含 Service Ticket,如果沒有,則說明當前用戶尚未登錄,於是將請求重定向到指定好的 CAS Server 登錄地址,並傳遞 Service (也就是要訪問的目的資源地址),以便登錄成功過後轉回該地址。用戶在第 3 步中輸入認證信息,如果登錄成功,CAS Server 隨機產生一個相當長度、唯一、不可僞造的 Service Ticket,並緩存以待將來驗證,之後系統自動重定向到 Service 所在地址,併爲客戶端瀏覽器設置一個 Ticket Granted Cookie(TGC),CAS Client 在拿到 Service 和新產生的 Ticket 過後,在第 5,6 步中與 CAS Server 進行身份合適,以確保 Service Ticket 的合法性。

在該協議中,所有與 CAS 的交互均採用 SSL 協議,確保,ST 和 TGC 的安全性。協議工作過程中會有 2 次重定向的過程,但是 CAS Client 與 CAS Server 之間進行 Ticket 驗證的過程對於用戶是透明的。

另外,CAS 協議中還提供了 Proxy (代理)模式,以適應更加高級、複雜的應用場景,具體介紹可以參考 CAS 官方網站上的相關文檔。

準備工作

本文中的例子以 tomcat5.5 爲例進行講解,下載地址:

http://tomcat.apache.org/download-55.cgi

到 CAS 官方網站下載 CAS Server 和 Client,地址分別爲:

http://www.ja-sig.org/downloads/cas/cas-server-3.1.1-release.zip

http://www.ja-sig.org/downloads/cas-clients/cas-client-java-2.1.1.zip

 

部署 CAS Server

CAS Server 是一套基於 Java 實現的服務,該服務以一個 Java Web Application 單獨部署在與 servlet2.3 兼容的 Web 服務器上,另外,由於 Client 與 CAS Server 之間的交互採用 Https 協議,因此部署 CAS Server 的服務器還需要支持 SSL 協議。當 SSL 配置成功過後,像普通 Web 應用一樣將 CAS Server 部署在服務器上就能正常運行了,不過,在真正使用之前,還需要擴展驗證用戶的接口。

在 Tomcat 上部署一個完整的 CAS Server 主要按照以下幾個步驟:

配置 Tomcat 使用 Https 協議

如果希望 Tomcat 支持 Https,主要的工作是配置 SSL 協議,其配置過程和配置方法可以參考 Tomcat 的相關文檔。不過在生成證書的過程中,會有需要用到主機名的地方,CAS 建議不要使用 IP 地址,而要使用機器名或域名。

部署 CAS Server

CAS Server 是一個 Web 應用包,將前面下載的 cas-server-3.1.1-release.zip 解開,把其中的 cas-server-webapp-3.1.1.war 拷貝到 tomcat的 webapps 目錄,並更名爲 cas.war。由於前面已配置好 tomcat 的 https 協議,可以重新啓動 tomcat,然後訪問:https://localhost:8443/cas ,如果能出現正常的 CAS 登錄頁面,則說明 CAS Server 已經部署成功。

雖然 CAS Server 已經部署成功,但這只是一個缺省的實現,在實際使用的時候,還需要根據實際概況做擴展和定製,最主要的是擴展認證 (Authentication) 接口和 CAS Server 的界面。

擴展認證接口

CAS Server 負責完成對用戶的認證工作,它會處理登錄時的用戶憑證 (Credentials) 信息,用戶名/密碼對是最常見的憑證信息。CAS Server 可能需要到數據庫檢索一條用戶帳號信息,也可能在 XML 文件中檢索用戶名/密碼,還可能通過 LDAP Server 獲取等,在這種情況下,CAS 提供了一種靈活但統一的接口和實現分離的方式,實際使用中 CAS 採用哪種方式認證是與 CAS 的基本協議分離開的,用戶可以根據認證的接口去定製和擴展。

擴展 AuthenticationHandler

CAS 提供擴展認證的核心是 AuthenticationHandler 接口,該接口定義如清單 1 下:


清單 1. AuthenticationHandler定義

public interface AuthenticationHandler {
/**
* Method to determine if the credentials supplied are valid.
* @param credentials The credentials to validate.
* @return true if valid, return false otherwise.
* @throws AuthenticationException An AuthenticationException can contain
* details about why a particular authentication request failed.
*/
boolean authenticate(Credentials credentials) throws AuthenticationException;
/**
* Method to check if the handler knows how to handle the credentials
* provided. It may be a simple check of the Credentials class or something
* more complicated such as scanning the information contained in the
* Credentials object. 
* @param credentials The credentials to check.
* @return true if the handler supports the Credentials, false othewrise.
*/
boolean supports(Credentials credentials);
}
 

 

該接口定義了 2 個需要實現的方法,supports ()方法用於檢查所給的包含認證信息的Credentials 是否受當前 AuthenticationHandler 支持;而 authenticate() 方法則擔當驗證認證信息的任務,這也是需要擴展的主要方法,根據情況與存儲合法認證信息的介質進行交互,返回 boolean 類型的值,true 表示驗證通過,false 表示驗證失敗。

CAS3中還提供了對AuthenticationHandler 接口的一些抽象實現,比如,可能需要在執行authenticate() 方法前後執行某些其他操作,那麼可以讓自己的認證類擴展自清單 2 中的抽象類:


清單 2. AbstractPreAndPostProcessingAuthenticationHandler定義

 

                
public abstract class AbstractPreAndPostProcessingAuthenticationHandler 
                                           implements AuthenticateHandler{
    protected Log log = LogFactory.getLog(this.getClass());
    protected boolean preAuthenticate(final Credentials credentials) {
        return true;
    }
    protected boolean postAuthenticate(final Credentials credentials,
        final boolean authenticated) {
        return authenticated;
    }
    public final boolean authenticate(final Credentials credentials)
        throws AuthenticationException {
        if (!preAuthenticate(credentials)) {
            return false;
        }
        final boolean authenticated = doAuthentication(credentials);
        return postAuthenticate(credentials, authenticated);
    }
    protected abstract boolean doAuthentication(final Credentials credentials) 
throws AuthenticationException;
}
 

 

 

AbstractPreAndPostProcessingAuthenticationHandler 類新定義了 preAuthenticate() 方法和 postAuthenticate() 方法,而實際的認證工作交由 doAuthentication() 方法來執行。因此,如果需要在認證前後執行一些額外的操作,可以分別擴展 preAuthenticate()和 ppstAuthenticate() 方法,而 doAuthentication() 取代 authenticate() 成爲了子類必須要實現的方法。

由於實際運用中,最常用的是用戶名和密碼方式的認證,CAS3 提供了針對該方式的實現,如清單 3 所示:


清單 3. AbstractUsernamePasswordAuthenticationHandler 定義

 

public abstract class AbstractUsernamePasswordAuthenticationHandler extends 
                       AbstractPreAndPostProcessingAuthenticationHandler{
...
 protected final boolean doAuthentication(final Credentials credentials)
 throws AuthenticationException {
 return authenticateUsernamePasswordInternal((UsernamePasswordCredentials) credentials);
 }
 protected abstract boolean authenticateUsernamePasswordInternal(
        final UsernamePasswordCredentials credentials) throws AuthenticationException;   
protected final PasswordEncoder getPasswordEncoder() {
 return this.passwordEncoder;
 }
public final void setPasswordEncoder(final PasswordEncoder passwordEncoder) {
 this.passwordEncoder = passwordEncoder;
    }
...
}
 

 

基於用戶名密碼的認證方式可直接擴展自 AbstractUsernamePasswordAuthenticationHandler,驗證用戶名密碼的具體操作通過實現 authenticateUsernamePasswordInternal() 方法達到,另外,通常情況下密碼會是加密過的,setPasswordEncoder() 方法就是用於指定適當的加密器。

從以上清單中可以看到,doAuthentication() 方法的參數是 Credentials 類型,這是包含用戶認證信息的一個接口,對於用戶名密碼類型的認證信息,可以直接使用 UsernamePasswordCredentials,如果需要擴展其他類型的認證信息,需要實現Credentials接口,並且實現相應的 CredentialsToPrincipalResolver 接口,其具體方法可以借鑑 UsernamePasswordCredentials 和 UsernamePasswordCredentialsToPrincipalResolver。

JDBC 認證方法

用戶的認證信息通常保存在數據庫中,因此本文就選用這種情況來介紹。將前面下載的 cas-server-3.1.1-release.zip 包解開後,在 modules 目錄下可以找到包 cas-server-support-jdbc-3.1.1.jar,其提供了通過 JDBC 連接數據庫進行驗證的缺省實現,基於該包的支持,我們只需要做一些配置工作即可實現 JDBC 認證。

JDBC 認證方法支持多種數據庫,DB2, Oracle, MySql, Microsoft SQL Server 等均可,這裏以 DB2 作爲例子介紹。並且假設DB2數據庫名: CASTest,數據庫登錄用戶名: db2user,數據庫登錄密碼: db2password,用戶信息表爲: userTable,該表包含用戶名和密碼的兩個數據項分別爲 userName 和 password。

1. 配置 DataStore

打開文件 %CATALINA_HOME%/webapps/cas/WEB-INF/deployerConfigContext.xml,添加一個新的 bean 標籤,對於 DB2,內容如清單 4 所示:


清單 4. 配置 DataStore

 

<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.125.65.134:50000/CASTest</value>
     </property>
     <property name="username">
          <value>db2user</value>
     </property>
     <property name="password">
          <value>db2password</value>
     </property>
</bean>
 

 


2. 配置 AuthenticationHandler
其中 id 屬性爲該 DataStore 的標識,在後面配置 AuthenticationHandler 會被引用,另外,需要提供 DataStore 所必需的數據庫驅動程序、連接地址、數據庫登錄用戶名以及登錄密碼。

在 cas-server-support-jdbc-3.1.1.jar 包中,提供了 3 個基於 JDBC 的 AuthenticationHandler,分別爲 BindModeSearchDatabaseAuthenticationHandler, QueryDatabaseAuthenticationHandler, SearchModeSearchDatabaseAuthenticationHandler。其中 BindModeSearchDatabaseAuthenticationHandler 是用所給的用戶名和密碼去建立數據庫連接,根據連接建立是否成功來判斷驗證成功與否;QueryDatabaseAuthenticationHandler 通過配置一個 SQL 語句查出密碼,與所給密碼匹配;SearchModeSearchDatabaseAuthenticationHandler 通過配置存放用戶驗證信息的表、用戶名字段和密碼字段,構造查詢語句來驗證。

使用哪個 AuthenticationHandler,需要在 deployerConfigContext.xml 中設置,默認情況下,CAS 使用一個簡單的 username=password 的 AuthenticationHandler,在文件中可以找到如下一行:<bean class="org.jasig.cas.authentication.handler.support.SimpleTestUsernamePassword
AuthenticationHandler" />,我們可以將其註釋掉,換成我們希望的一個 AuthenticationHandler,比如,使用QueryDatabaseAuthenticationHandler 或 SearchModeSearchDatabaseAuthenticationHandler 可以分別選取清單 5 或清單 6 的配置。


清單 5. 使用 QueryDatabaseAuthenticationHandler

 

<bean class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">
 <property name="dataSource" ref=" casDataSource " />
 <property name="sql" 
       value="select password from userTable where lower(userName) = lower(?)" />
</bean>

 

清單 6. 使用 SearchModeSearchDatabaseAuthenticationHandler

 

 

<bean id="SearchModeSearchDatabaseAuthenticationHandler"
      class="org.jasig.cas.adaptors.jdbc.SearchModeSearchDatabaseAuthenticationHandler"
      abstract="false" singleton="true" lazy-init="default" 
                       autowire="default" dependency-check="default">
  <property  name="tableUsers">
   <value>userTable</value>
  </property>
  <property name="fieldUser">
   <value>userName</value>
  </property>
  <property name="fieldPassword">
   <value>password</value>
  </property>
  <property name="dataSource" ref=" casDataSource " />
</bean>
 

 

另外,由於存放在數據庫中的密碼通常是加密過的,所以 AuthenticationHandler 在匹配時需要知道使用的加密方法,在 deployerConfigContext.xml 文件中我們可以爲具體的 AuthenticationHandler 類配置一個 property,指定加密器類,比如對於 QueryDatabaseAuthenticationHandler,可以修改如清單7所示:


清單 7. 添加 passwordEncoder

 

<bean class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">
  <property name="dataSource" ref=" casDataSource " />
  <property name="sql" 
           value="select password from userTable where lower(userName) = lower(?)" />
  <property  name="passwordEncoder"  ref="myPasswordEncoder"/>
</bean>
 

 

其中 myPasswordEncoder 是對清單 8 中設置的實際加密器類的引用:

清單 8. 指定具體加密器類

 

<bean id="passwordEncoder" 
            class="org.jasig.cas.authentication.handler.MyPasswordEncoder"/>
 

 

這裏 MyPasswordEncoder 是根據實際情況自己定義的加密器,實現 PasswordEncoder 接口及其 encode() 方法。

3. 部署依賴包

在以上配置完成以後,需要拷貝幾個依賴的包到 cas 應用下,包括:

  • 將 cas-server-support-jdbc-3.1.1.jar 拷貝到 %CATALINA_HOME%/webapps/cas/ WEB-INF/lib 目錄。
  • 數據庫驅動,由於這裏使用 DB2,將 %DB2_HOME%/java 目錄下的 db2java.zip (更名爲 db2java.jar), db2jcc.jar, db2jcc_license_cu.jar 拷貝到 %CATALINA_HOME%/webapps/cas/WEB-INF/lib 目錄。對於其他數據庫,同樣將相應數據庫驅動程序拷貝到該目錄。
  • DataStore 依賴於 commons-collections-3.2.jar, commons-dbcp-1.2.1.jar, commons-pool-1.3.jar,需要到 apache 網站的 Commons 項目下載以上 3 個包放進 %CATALINA_HOME%/webapps/cas/WEB-INF/lib 目錄。

擴展 CAS Server 界面

CAS 提供了 2 套默認的頁面,分別爲“ default ”和“ simple ”,分別在目錄“ cas/WEB-INF/view/jsp/default ”和“ cas/WEB-INF/view/jsp/simple ”下。其中 default 是一個稍微複雜一些的頁面,使用 CSS,而 simple 則是能讓 CAS 正常工作的最簡化的頁面。

在部署 CAS 之前,我們可能需要定製一套新的 CAS Server 頁面,添加一些個性化的內容。最簡單的方法就是拷貝一份 default 或 simple 文件到“ cas/WEB-INF/view/jsp ”目錄下,比如命名爲 newUI,接下來是實現和修改必要的頁面,有 4 個頁面是必須的:

  • casConfirmView.jsp: 當用戶選擇了“ warn ”時會看到的確認界面
  • casGenericSuccess.jsp: 在用戶成功通過認證而沒有目的Service時會看到的界面
  • casLoginView.jsp: 當需要用戶提供認證信息時會出現的界面
  • casLogoutView.jsp: 當用戶結束 CAS 單點登錄系統會話時出現的界面

CAS 的頁面採用 Spring 框架編寫,對於不熟悉 Spring 的使用者,在修改之前需要熟悉該框架。

頁面定製完過後,還需要做一些配置從而讓 CAS 找到新的頁面,拷貝“ cas/WEB-INF/classes/default_views.properties ”,重命名爲“ cas/WEB-INF/classes/ newUI_views.properties ”,並修改其中所有的值到相應新頁面。最後是更新“ cas/WEB-INF/cas-servlet.xml ”文件中的 viewResolver,將其修改爲如清單 9 中的內容。


清單 9. 指定 CAS 頁面

 

<bean id="viewResolver" 
     class="org.springframework.web.servlet.view.ResourceBundleViewResolver" p:order="0">
    <property name="basenames">
        <list>
            <value>${cas.viewResolver.basename}</value>
            <value> newUI_views</value>
        </list>
    </property>
</bean>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章