CAS客戶端與SpringSecurity集成

4. CAS客戶端與SpringSecurity集成

4.1 Spring Security測試工程搭建

1)創建Maven項目casclient_demo3 ,引入spring依賴和spring secrity 相關依賴 ,tomcat端口設置爲9003javascript

2)創建web.xml ,添加過濾器等配置css

3)建立配置文件spring-security.xml html

4)添加html頁面java

4.2 Spring SecurityCAS集成

1)引入依賴angularjs

<dependency>  web

   <groupId>org.springframework.security</groupId>  spring

   <artifactId>spring-security-cas</artifactId>  express

   <version>4.1.0.RELEASE</version>  後端

</dependency>     tomcat

<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);

}

}

這個類的主要做用是在登錄後獲得用戶名,能夠根據用戶名查詢角色或執行一些邏輯。

4.3獲取登陸名

咱們在處理後端邏輯須要得到登陸名,那麼如何獲取單點登陸的用戶名呢? 其實和咱們以前得到用戶名的方式是徹底相同的,咱們下面來作個測試。

1web.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.itcast.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.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>

 

5.品優購用戶中心

5.1需求分析

用戶中心實現單點登陸。

5.2代碼實現

5.2.1用戶中心實現單點登陸

(1)將用戶中心相關的頁面(home-開頭的)拷貝至  pinnyougou-user-web  

 

2pom.xml 引入springSecuritycas客戶端和springSecurity Cas整合包依賴(參照casclient_demo3)。

3web.xml  添加spring-security過濾器(參照參照casclient_demo3)設置首頁爲home-index.html

<welcome-file-list>

<welcome-file>home-index.html</welcome-file>

</welcome-file-list>

4)構建UserDetailsServiceImpl.java  (參照casclient_demo3

 

(5)添加spring-security.xml(參照casclient_demo3),並作如下修改

配置匿名訪問資源

<!-- 匿名訪問資源 -->

<http pattern="/css/**" security="none"></http>

<http pattern="/js/**" security="none"></http>

<http pattern="/image/**" security="none"></http>

<http pattern="/plugins/**" security="none"></http>

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

<http pattern="/user/add.do" security="none"></http>

<http pattern="/user/sendCode.do" security="none"></http>

設置服務地址屬性

<beans:bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">    

     <beans:property name="service" value="http://localhost:9106/login/cas"/>

</beans:bean>  

設置認證類

<beans:bean

id="userDetailsService" class="com.pinyougou.user.service.UserDetailServiceImpl"/>  

5.2.2頁面顯示用戶名

1pinyougou-user-web建立LoginController.java

@RestController

@RequestMapping("/login")

public class LoginController {

@RequestMapping("/name")

public Map showName(){

String name = SecurityContextHolder.getContext().getAuthentication().getName();//獲得登錄人帳號

Map map=new HashMap<>();

map.put("loginName", name);

return map;

}

}

2)建立loginService.js

//服務層

app.service('loginService',function($http){

//讀取列表數據綁定到表單中

this.showName=function(){

return $http.get('../login/name.do');

}

});

3)建立indexController.js

//首頁控制器

app.controller('indexController',function($scope,loginService){

$scope.showName=function(){

loginService.showName().success(

function(response){

$scope.loginName=response.loginName;

}

);

}

});

5)修改home-index.html  引入js

    <script type="text/javascript" src="plugins/angularjs/angular.min.js"></script>

<script type="text/javascript" src="js/base.js"></script>

<script type="text/javascript" src="js/service/loginService.js"></script>

<script type="text/javascript" src="js/controller/indexController.js"></script>

指令,調用方法查詢登錄名

<body ng-app="pinyougou" ng-controller="indexController" ng-init="showName()">

顯示用戶名

 <span class="name">{{loginName}}</span>

5.2.3退出登陸

設置退出登陸後的跳轉地址

<beans:bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">  

        <beans:constructor-arg value="http://localhost:9100/cas/logout?service=http://localhost:9103"/>  

       ........  

</beans:bean>  

退出登陸後,跳轉到網站首頁

<span class="safe"> <a href="/logout/cas">退出登陸 </a></span>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

附錄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

 

 

完畢,good luck!

相關文章
相關標籤/搜索