1. 程式人生 > >CAS客戶端與SpringSecurity整合

CAS客戶端與SpringSecurity整合

1、Spring Security測試工程搭建

(1)建立Maven專案casclient_demo3 ,引入spring依賴和spring secrity 相關依賴 ,tomcat埠設定為9003。
(2)建立web.xml ,新增過濾器等配置。
(3)建立配置檔案spring-security.xml。 
(4)新增html頁面。

2、Spring Security CAS整合

    (1)引入依賴   

<dependency>  
	   <groupId>org.springframework.security</groupId>  
	   <artifactId>spring-security-cas</artifactId>  
	   <version>4.1.0.RELEASE</version>  
</dependency>     
<dependency>  
        <groupId>org.jasig.cas.client</groupId>  
        <artifactId>cas-client-core</artifactId>  
        <version>3.3.3</version>  
        <exclusions>  
            <exclusion>  
                <groupId>org.slf4j</groupId>  
                <artifactId>log4j-over-slf4j</artifactId>  
            </exclusion>  
        </exclusions>  
</dependency> 

(2)修改spring-security.xml  

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
						http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
	
	<!--   entry-point-ref  入口點引用 -->
	<http use-expressions="false" entry-point-ref="casProcessingFilterEntryPoint">  
        <intercept-url pattern="/**" access="ROLE_USER"/>   
        <csrf disabled="true"/>  
        <!-- custom-filter為過濾器, position 表示將過濾器放在指定的位置上,before表示放在指定位置之前  ,after表示放在指定的位置之後  -->           
        <custom-filter ref="casAuthenticationFilter"  position="CAS_FILTER" />      
        <custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER"/>  
        <custom-filter ref="singleLogoutFilter" before="CAS_FILTER"/>  
    </http>
    
  	<!-- CAS入口點 開始 -->
    <beans:bean id="casProcessingFilterEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">  
        <!-- 單點登入伺服器登入URL -->  
        <beans:property name="loginUrl" value="http://localhost:9100/cas/login"/>  
        <beans:property name="serviceProperties" ref="serviceProperties"/>  
    </beans:bean>      
    <beans:bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">  
        <!--service 配置自身工程的根地址+/login/cas   -->  
        <beans:property name="service" value="http://localhost:9003/login/cas"/>
    </beans:bean>  
    <!-- CAS入口點 結束 -->
   
    <!-- 認證過濾器 開始 -->
    <beans:bean id="casAuthenticationFilter" class="org.springframework.security.cas.web.CasAuthenticationFilter">  
        <beans:property name="authenticationManager" ref="authenticationManager"/>  
    </beans:bean>  
		<!-- 認證管理器 -->
	<authentication-manager alias="authenticationManager">
		<authentication-provider  ref="casAuthenticationProvider">
		</authentication-provider>
	</authentication-manager>
		<!-- 認證提供者 -->
	<beans:bean id="casAuthenticationProvider"     class="org.springframework.security.cas.authentication.CasAuthenticationProvider">  
        <beans:property name="authenticationUserDetailsService">  
            <beans:bean class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">  
                <beans:constructor-arg ref="userDetailsService" />  
            </beans:bean>  
        </beans:property>  
        <beans:property name="serviceProperties" ref="serviceProperties"/>  
        <!-- ticketValidator 為票據驗證器 -->
        <beans:property name="ticketValidator">  
            <beans:bean class="org.jasig.cas.client.validation.Cas20ServiceTicketValidator">  
                <beans:constructor-arg index="0" value="http://localhost:9100/cas"/>  
            </beans:bean>  
        </beans:property>  
        <beans:property name="key" value="an_id_for_this_auth_provider_only"/> 
    </beans:bean>        
   		 <!-- 認證類 -->
	<beans:bean id="userDetailsService" class="cn.itcast.demo.service.UserDetailServiceImpl"/>  
	
	<!-- 認證過濾器 結束 -->
	<!-- 單點登出  開始  -->     
    <beans:bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter"/>          
    <beans:bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">  
        <beans:constructor-arg value="http://localhost:9100/cas/logout?service=http://www.baidu.com"/>  
        <beans:constructor-arg>  
            <beans:bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>  
        </beans:constructor-arg>  
        <beans:property name="filterProcessesUrl" value="/logout/cas"/>  
    </beans:bean>  
    <!-- 單點登出  結束 -->  
</beans:beans>

(3)建立UserDetailsServiceImpl 

/**
 * 認證類
 */
public class UserDetailServiceImpl implements UserDetailsService {
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//構建角色集合
		List<GrantedAuthority> authorities=new ArrayList();
		authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
		return new User(username, ""  , authorities);		
	}
}

這個類的主要作用是在登陸後得到使用者名稱,可以根據使用者名稱查詢角色或執行一些邏輯。

3、獲取登入名

    我們在處理後端邏輯需要獲得登入名,那麼如何獲取單點登入的使用者名稱呢? 其實和我們之前獲得使用者名稱的方式是完全相同的,我們下面來做個測試。

(1)web.xml 新增springmvc

    
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<!-- 指定載入的配置檔案 ,通過引數contextConfigLocation載入-->
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:springmvc.xml</param-value>
  	</init-param>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>

(2)建立springmvc.xml

	<context:component-scan base-package="cn.newbie.demo" />
	<mvc:annotation-driven />

(3)建立UserController 

@RestController
public class UserController {
	@RequestMapping("/findLoginUser")
	public void  findLoginUser(){
		String name = SecurityContextHolder.getContext().getAuthentication().getName();
		System.out.println(name);		
	}	
}

位址列輸入http://localhost:9003/findLoginUser.do即可在控制檯看到輸出的登入名。

4、退出登入    

修改spring-security.xml 

<beans:bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">  
        <beans:constructor-arg value="http://localhost:9100/cas/logout?service=http://localhost:9003/index2.html"/>  
        <beans:constructor-arg>  
            <beans:bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>  
        </beans:constructor-arg>  
        <beans:property name="filterProcessesUrl" value="/logout/cas"/>  
</beans:bean>

在頁面上新增連結

<a href="/logout/cas">退出登入</a>

建立index2.html,將index2.html設定為可匿名訪問

<http pattern="/index2.html" security="none"></http>

附錄A. Spring Security 內建過濾器表

別名

Filter 類

CHANNEL_FILTER

ChannelProcessingFilter

SECURITY_CONTEXT_FILTER

SecurityContextPersistenceFilter

CONCURRENT_SESSION_FILTER

ConcurrentSessionFilter

LOGOUT_FILTER

LogoutFilter

X509_FILTER

X509AuthenticationFilter

PRE_AUTH_FILTER

AstractPreAuthenticatedProcessingFilter 的子類

CAS_FILTER

CasAuthenticationFilter

FORM_LOGIN_FILTER

UsernamePasswordAuthenticationFilter

BASIC_AUTH_FILTER

BasicAuthenticationFilter

SERVLET_API_SUPPORT_FILTER

SecurityContextHolderAwareRequestFilter

JAAS_API_SUPPORT_FILTER

JaasApiIntegrationFilter

REMEMBER_ME_FILTER

RememberMeAuthenticationFilter

ANONYMOUS_FILTER

AnonymousAuthenticationFilter

SESSION_MANAGEMENT_FILTER

SessionManagementFilter

EXCEPTION_TRANSLATION_FILTER

ExceptionTranslationFilter

FILTER_SECURITY_INTERCEPTOR

FilterSecurityInterceptor

SWITCH_USER_FILTER

SwitchUserFilter