Spring Security3對CAS的支持主要在這個(gè)spring-security-cas-client-3.0.2.RELEASE.jar包中
Spring Security和CAS集成的配置資料很多。這里講解的比較詳細
http://lengyun3566.iteye.com/blog/1358323
配置方面,主要為下面的部分:
- <security:http auto-config="true" entry-point-ref="casAuthEntryPoint" access-denied-page="/error/403.jsp">
- <security:custom-filter ref="casAuthenticationFilter" position="CAS_FILTER"/>
- <security:form-login login-page="/login.jsp"/>
- <security:logout logout-success-url="/login.jsp"/>
- <security:intercept-url pattern="/admin.jsp*" access="ROLE_ADMIN"/>
- <security:intercept-url pattern="/index.jsp*" access="ROLE_USER,ROLE_ADMIN"/>
- <security:intercept-url pattern="/home.jsp*" access="ROLE_USER,ROLE_ADMIN"/>
- <security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
- </security:http>
-
- <security:authentication-manager alias="authenticationmanager">
- <security:authentication-provider ref="casAuthenticationProvider"/>
- </security:authentication-manager>
-
- <bean id="casAuthenticationProvider" class="org.springframework.security.cas.authentication.CasAuthenticationProvider">
- <property name="ticketValidator" ref="casTicketValidator"/>
- <property name="serviceProperties" ref="casService"/>
- <property name="key" value="docms"/>
- <property name="authenticationUserDetailsService" ref="authenticationUserDetailsService"/>
- </bean>
-
- <bean id="casAuthEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">
- <property name="loginUrl" value="https://server:8443/cas/login"/>
- <property name="serviceProperties" ref="casService"/>
- </bean>
-
- <bean id="casService" class="org.springframework.security.cas.ServiceProperties">
- <property name="service" value="http://localhost:8888/docms/j_spring_cas_security_check"/>
- </bean>
-
- <bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">
- <property name="authenticationManager" ref="authenticationmanager"/>
- </bean>
-
- <bean id="casTicketValidator" class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">
- <constructor-arg value="https://server:8443/cas/"/>
- </bean>
-
- <bean id="authenticationUserDetailsService" class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
- <property name="userDetailsService" ref="userDetailsManager"/>
- </bean>
這里需要強調一下http標簽的entry-point-ref屬性,因為之前沒(méi)有著(zhù)重的介紹,英文的意思是入口點(diǎn)引用。為什么需要這個(gè)入口點(diǎn)呢。這個(gè)入口點(diǎn)其實(shí)僅僅是被ExceptionTranslationFilter引用的。前面已經(jīng)介紹過(guò)ExceptionTranslationFilter過(guò)濾器的作用是異常翻譯,在出現認證異常、訪(fǎng)問(wèn)異常時(shí),通過(guò)入口點(diǎn)決定redirect、forward的操作。比如現在是form-login的認證方式,如果沒(méi)有通過(guò)UsernamePasswordAuthenticationFilter的認證就直接訪(fǎng)問(wèn)某個(gè)被保護的url,那么經(jīng)過(guò)ExceptionTranslationFilter過(guò)濾器處理后,先捕獲到訪(fǎng)問(wèn)拒絕異常,并把跳轉動(dòng)作交給入口點(diǎn)來(lái)處理。form-login的對應入口點(diǎn)類(lèi)為L(cháng)oginUrlAuthenticationEntryPoint,這個(gè)入口點(diǎn)類(lèi)的commence方法會(huì )redirect或forward到指定的url(form-login標簽的login-page屬性)
清楚了entry-point-ref屬性的意義。那么與CAS集成時(shí),如果訪(fǎng)問(wèn)一個(gè)受保護的url,就通過(guò)CAS認證對應的入口點(diǎn)org.springframework.security.cas.web.CasAuthenticationEntryPoint類(lèi)redirect到loginUrl屬性所配置的url中,即一般為CAS的認證頁(yè)面(比如:https://server:8443/cas/login)。
下面為CasAuthenticationEntryPoint類(lèi)的commence方法。其主要任務(wù)就是構造跳轉的url,再執行redirect動(dòng)作。根據上面的配置,實(shí)際上跳轉的url為:https://server:8443/cas/login?service=http%3A%2F%2Flocalhost%3A8888%2Fdocms%2Fj_spring_cas_security_check
- public final void commence(final HttpServletRequest servletRequest, final HttpServletResponse response,
- final AuthenticationException authenticationException) throws IOException, ServletException {
-
- final String urlEncodedService = createServiceUrl(servletRequest, response);
- final String redirectUrl = createRedirectUrl(urlEncodedService);
-
- preCommence(servletRequest, response);
- response.sendRedirect(redirectUrl);
- }
接下來(lái)繼續分析custom-filter ref="casAuthenticationFilter" position="CAS_FILTER"
這是一個(gè)自定義標簽,并且在過(guò)濾器鏈中的位置是CAS_FILTER。這個(gè)過(guò)濾器在何時(shí)會(huì )起作用呢?帶著(zhù)這個(gè)疑問(wèn)繼續閱讀源碼
CasAuthenticationFilter對應的類(lèi)路徑是
org.springframework.security.cas.web.CasAuthenticationFilter
這個(gè)類(lèi)與UsernamePasswordAuthenticationFilter一樣,都繼承于A(yíng)bstractAuthenticationProcessingFilter。實(shí)際上所有認證過(guò)濾器都繼承這個(gè)抽象類(lèi),其過(guò)濾器本身只要實(shí)現attemptAuthentication方法即可。
CasAuthenticationFilter的構造方法直接向父類(lèi)的構造方法傳入/j_spring_cas_security_check用于判斷當前請求的url是否需要進(jìn)一步的認證處理
- public CasAuthenticationFilter() {
- super("/j_spring_cas_security_check");
- }
CasAuthenticationFilter類(lèi)的attemptAuthentication方法源碼如下
- public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response)
- throws AuthenticationException {
-
- final String username = CAS_STATEFUL_IDENTIFIER;
-
- String password = request.getParameter(this.artifactParameter);
-
- if (password == null) {
- password = "";
- }
-
- final UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
-
- authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
-
- return this.getAuthenticationManager().authenticate(authRequest);
- }
在之前的源碼分析中,已經(jīng)詳細分析了認證管理器AuthenticationManager認證的整個(gè)過(guò)程,這里就不再贅述了。
由于A(yíng)uthenticationManager是依賴(lài)于具體的AuthenticationProvider的,所以接下來(lái)看
- <security:authentication-manager alias="authenticationmanager">
- <security:authentication-provider ref="casAuthenticationProvider"/>
- </security:authentication-manager>
注意這里的ref屬性定義。如果沒(méi)有使用CAS認證,此處一般定義user-service-ref屬性。這兩個(gè)屬性的區別在于
ref:直接將ref依賴(lài)的bean注入到AuthenticationProvider的providers集合中
user-service-ref:定義DaoAuthenticationProvider的bean注入到AuthenticationProvider的providers集合中,并且DaoAuthenticationProvider的變量userDetailsService由user-service-ref依賴(lài)的bean注入。
由此可見(jiàn),采用CAS認證時(shí),AuthenticationProvider只有AnonymousAuthenticationProvider和CasAuthenticationProvider
繼續分析CasAuthenticationProvider是如何完成認證工作的
- public Authentication authenticate(Authentication authentication) throws AuthenticationException {
-
- CasAuthenticationToken result = null;
-
- if (stateless) {
-
-
- result = statelessTicketCache.getByTicketId(authentication.getCredentials().toString());
- }
-
- if (result == null) {
- result = this.authenticateNow(authentication);
- result.setDetails(authentication.getDetails());
- }
-
- if (stateless) {
-
- statelessTicketCache.putTicketInCache(result);
- }
-
- return result;
- }
-
-
- private CasAuthenticationToken authenticateNow(final Authentication authentication) throws AuthenticationException {
- try {
-
- final Assertion assertion = this.ticketValidator.validate(authentication.getCredentials().toString(), serviceProperties.getService());
-
- final UserDetails userDetails = loadUserByAssertion(assertion);
-
- userDetailsChecker.check(userDetails);
-
- return new CasAuthenticationToken(this.key, userDetails, authentication.getCredentials(), userDetails.getAuthorities(), userDetails, assertion);
- } catch (final TicketValidationException e) {
- throw new BadCredentialsException(e.getMessage(), e);
- }
- }
-
-
- protected UserDetails loadUserByAssertion(final Assertion assertion) {
- final CasAssertionAuthenticationToken token = new CasAssertionAuthenticationToken(assertion, "");
- return this.authenticationUserDetailsService.loadUserDetails(token);
- }
需要注意的是為什么要定義authenticationUserDetailsService這個(gè)bean。由于CAS需要authentication-manager標簽下定義<security:authentication-provider ref="casAuthenticationProvider"/>,而不是之前所介紹的
user-service-ref屬性,所以這里僅僅定義了一個(gè)provider,而沒(méi)有注入UserDetailsService,所以這里需要單獨定義authenticationUserDetailsService這個(gè)bean,并注入到CasAuthenticationProvider中。
這里需要對CasAuthenticationToken、CasAssertionAuthenticationToken單獨解釋一下
CasAuthenticationToken:一個(gè)成功通過(guò)的CAS認證,與UsernamePasswordAuthenticationToken一樣,都是繼承于A(yíng)bstractAuthenticationToken,并且最終會(huì )保存到SecurityContext上下文、session中
CasAssertionAuthenticationToken:一個(gè)臨時(shí)的認證對象用于輔助獲取UserDetails
配置文件中幾個(gè)bean定義這里就不一一分析了,都是為了輔助完成CAS認證、跳轉的工作。
現在,可以對整個(gè)CAS認證的過(guò)程總結一下了:
1.客戶(hù)端發(fā)起一個(gè)請求,試圖訪(fǎng)問(wèn)系統系統中受保護的url
2.各filter鏈進(jìn)行攔截并做相應處理,由于沒(méi)有通過(guò)認證,ExceptionTranslationFilter過(guò)濾器會(huì )捕獲到訪(fǎng)問(wèn)拒絕異常,并把該異常交給入口點(diǎn)處理
3.CAS 認證對應的入口點(diǎn)直接跳轉到CAS Server端的登錄界面,并攜帶參數service(一般為url:……/j_spring_cas_security_check)
4.CAS Server對登錄信息進(jìn)行處理,如果登錄成功,就跳轉到應用系統中service指定的url,并攜帶ticket
5.應用系統中的各filter鏈再次對該url攔截,此時(shí)CasAuthenticationFilter攔截到j(luò )_spring_cas_security_check,就會(huì )對ticket進(jìn)行驗證,驗證成功返回一個(gè)身份斷言,再通過(guò)身份斷言從當前應用系統中獲取對應的UserDetails、GrantedAuthority。此時(shí),如果步驟1中受保護的url權限列表有一個(gè)權限存在于GrantedAuthority列表中,說(shuō)明有權限訪(fǎng)問(wèn),直接響應客戶(hù)端所試圖訪(fǎng)問(wèn)的url