開源單點登錄系統CAS入門


一、什么是CAS

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

  【1】開源的企業級單點登錄解決方案。

  【2】CAS Server 為需要獨立部署的 Web 應用。

  【3】CAS Client 支持非常多的客戶端(這里指單點登錄系統中的各個 Web 應用),包括 Java, .Net, PHP, Perl, Apache, uPortal, Ruby 等。

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

  

  SSO單點登錄訪問流程主要有以下步驟:

  1. 訪問服務:SSO客戶端發送請求訪問應用系統提供的服務資源。

  2. 定向認證:SSO客戶端會重定向用戶請求到SSO服務器。

  3. 用戶認證:用戶身份認證。

  4. 發放票據:SSO服務器會產生一個隨機的Service Ticket。

  5. 驗證票據:SSO服務器驗證票據Service Ticket的合法性,驗證通過后,允許客戶端訪問服務。

  6. 傳輸用戶信息:SSO服務器驗證票據通過后,傳輸用戶認證結果信息給客戶端。

二、CAS服務端部署

  下載CAS4.0.0(選擇4.0.0 的原因是:4.0.0以后打包比較麻煩,4.0.0版本內有打包好的war)。

  下載地址為:

   

  解壓cas-server-4.0.0-release.zip,將cas-server-4.0.0-release\cas-server-4.0.0\modules目錄下的cas-server-webapp-4.0.0.war改名為cas.war,並放入tomcat目錄下的webapps下。啟動tomcat自動解壓war包。瀏覽器輸入http://localhost:8080/cas ,即可看到登錄頁面

  

  這里有個固定的用戶名和密碼:casuser /Mellon

這個初始用戶名和密碼在cas\webapps\cas\WEB-INF\deployerConfigContext.xml中有配置  

  

  如果想新增一個用戶,增加一個<entry>標簽即可。

  登錄成功后會跳到登錄成功的提示頁面

  

三、CAS服務端配置

3.1 端口修改

  如果我們不希望用8080端口訪問CAS, 可以修改端口。

  (1)修改TOMCAT的端口

  打開tomcat 目錄 conf\server.xml  找到下面的配置

  

  將端口8080,改為9100

  (2)修改CAS配置文件

  修改cas的WEB-INF/cas.properties 

server.name=http://localhost:9100

3.2 去除https認證

  CAS默認使用的是HTTPS協議,如果使用HTTPS協議需要SSL安全證書(需向特定的機構申請和購買)。如果對安全要求不高或是在開發測試階段,可使用HTTP協議。我們這里講解通過修改配置,讓CAS使用HTTP協議。

  (1)修改cas的WEB-INF/deployerConfigContext.xml

  找到下面的配置

   

  這里需要增加參數p:requireSecure="false",requireSecure屬性意思為是否需要安全驗證,即HTTPS,false為不采用。

  (2)修改cas的/WEB-INF/spring-configuration/ticketGrantingTicketCookieGenerator.xml

  找到下面配置

   

  參數p:cookieSecure="true",同理為HTTPS驗證相關,TRUE為采用HTTPS驗證,FALSE為不采用https驗證。

  參數p:cookieMaxAge="-1",是COOKIE的最大生命周期,-1為無生命周期,即只在當前打開的窗口有效,關閉或重新打開其它窗口,仍會要求驗證。可以根據需要修改為大於0的數字,比如3600等,意思是在3600秒內,打開任意窗口,都不需要驗證。

  我們這里將cookieSecure改為false ,  cookieMaxAge 改為3600

  (3)修改cas的WEB-INF/spring-configuration/warnCookieGenerator.xml

  找到下面配置

  

  我們這里將cookieSecure改為false ,  cookieMaxAge 改為3600

四、CAS客戶端入門案例

4.1 客戶端工程1搭建

  (1)創建Maven工程 (war)casclient_demo1  引入cas客戶端依賴並制定tomcat運行端口為9001

<dependencies>
        <!-- cas -->  
        <dependency>  
            <groupId>org.jasig.cas.client</groupId>  
            <artifactId>cas-client-core</artifactId>  
            <version>3.3.3</version>  
        </dependency>          
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>  
            <scope>provided</scope>
        </dependency>
    </dependencies>  
  <build>  
      <plugins>
          <plugin>  
              <groupId>org.apache.maven.plugins</groupId>  
              <artifactId>maven-compiler-plugin</artifactId>  
              <version>2.3.2</version>  
              <configuration>  
                  <source>1.7</source>  
                  <target>1.7</target>  
              </configuration>  
          </plugin>  
          <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <configuration>
                    <!-- 指定端口 -->
                    <port>9001</port>
                    <!-- 請求路徑 -->
                    <path>/</path>
                </configuration>
            </plugin>
      </plugins>  
    </build>

  (2)添加web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
    <!-- 用於單點退出,該過濾器用於實現單點登出功能,可選配置 -->
    <listener>
        <listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class>
    </listener>
    <!-- 該過濾器用於實現單點登出功能,可選配置。 -->
    <filter>
        <filter-name>CAS Single Sign Out Filter</filter-name>
        <filter-class>org.jasig.cas.client.session.SingleSignOutFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CAS Single Sign Out Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 該過濾器負責用戶的認證工作,必須啟用它 -->
    <filter>
        <filter-name>CASFilter</filter-name>
        <filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class>
        <init-param>
            <param-name>casServerLoginUrl</param-name>
            <param-value>http://localhost:9100/cas/login</param-value>
            <!--這里的server是服務端的IP -->
        </init-param>
        <init-param>
            <param-name>serverName</param-name>
            <param-value>http://localhost:9001</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CASFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 該過濾器負責對Ticket的校驗工作,必須啟用它 -->
    <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://localhost:9100/cas</param-value>
        </init-param>
        <init-param>
            <param-name>serverName</param-name>
            <param-value>http://localhost:9001</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CAS Validation Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 該過濾器負責實現HttpServletRequest請求的包裹, 比如允許開發者通過HttpServletRequest的getRemoteUser()方法獲得SSO登錄用戶的登錄名,可選配置。 -->
    <filter>
        <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>
        <filter-class>
            org.jasig.cas.client.util.HttpServletRequestWrapperFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CAS HttpServletRequest Wrapper Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 該過濾器使得開發者可以通過org.jasig.cas.client.util.AssertionHolder來獲取用戶的登錄名。 比如AssertionHolder.getAssertion().getPrincipal().getName()。 -->
    <filter>
        <filter-name>CAS Assertion Thread Local Filter</filter-name>
        <filter-class>org.jasig.cas.client.util.AssertionThreadLocalFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CAS Assertion Thread Local Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

  (3)編寫index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
         pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>一品優購</title>
</head>
<body>
歡迎來到一品優購
<%=request.getRemoteUser()%>
</body>
</html>

  request.getRemoteUser()為獲取遠程登錄名

4.2 客戶端工程2搭建

  (1)創建Maven工程 (war)casclient_demo2  引入cas客戶端依賴並制定tomcat運行端口為9002

  (2)創建web.xml,參照casclient_demo1  ,將serverName的值改為http://localhost:9002,一共兩處

  (3)創建index.jsp  ,內容顯示“歡迎來到二品優購”

4.3 單點登錄測試

  (1)啟動cas部署的tomcat 

  (2)啟動客戶端工程1和客戶端工程2

  (3)地址欄輸入http://localhost:9001/ 和http://localhost:9002/ ,地址均會跳轉到CAS登錄頁

  (4)輸入用戶名和密碼后,頁面跳轉回9002,再次訪問9001也可以打開主頁面。

4.4 單點退出登錄

  地址欄輸入  http://localhost:9100/cas/logout

  即可看到退出后的提示頁面

  

  我們可以將這個鏈接添加到index.jsp中

<a href="http://localhost:9100/cas/logout">退出登錄</a>

  但我們更希望退出登錄后,能自動跳轉到某個頁面,那如何處理呢?

  修改cas系統的配置文件cas-servlet.xml

  

  改為true后,可以在退出時跳轉頁面到目標頁面,修改index.jsp的退出鏈接

<a href="http://localhost:9100/cas/logout?service=http://www.baidu.com">退出登錄</a>

五、CAS服務端數據源設置

【需求分析】  

  我們現在讓用戶名密碼從我們的品優購的user表里做驗證

【配置數據源】

  (1)修改cas服務端中WEB-INF下deployerConfigContext.xml ,添加如下配置

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"  
          p:driverClass="com.mysql.jdbc.Driver"  
          p:jdbcUrl="jdbc:mysql://127.0.0.1:3306/pinyougoudb?characterEncoding=utf8"  
          p:user="root"  
          p:password="root" /> 
<bean id="passwordEncoder" 
        class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder"  
        c:encodingAlgorithm="MD5"  
        p:characterEncoding="UTF-8" />  
<bean id="dbAuthHandler"  
          class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler"  
          p:dataSource-ref="dataSource"  
          p:sql="select password from tb_user where username = ?"  
          p:passwordEncoder-ref="passwordEncoder"/>  

  然后在配置文件開始部分找到如下配置

  

  其中

  是使用固定的用戶名和密碼,我們在下面可以看到這兩個bean ,如果我們使用數據庫認證用戶名和密碼,需要將這句注釋掉。

  添加下面這一句配置:

<entry key-ref="dbAuthHandler" value-ref="primaryPrincipalResolver"/>

  

  (2)將以下三個jar包放入webapps\cas\WEB-INF\lib下  

  

  用數據庫中的用戶名和密碼進行測試

六、CAS服務端界面改造 

  我們現在動手將CAS默認的登錄頁更改為自己的品優購登陸頁

6.1 改頭換面

【拷貝資源】

  (1)將品優購的登陸頁login.html拷貝到cas系統下WEB-INF\view\jsp\default\ui 目錄下

  (2)將css  js等文件夾拷貝到  cas目錄下

  (3) 將原來的casLoginView.jsp 改名(可以為之后的修改操作做參照),將login.html改名為casLoginView.jsp 

【修改頁面】

  編輯casLoginView.jsp 內容

   (1)添加指令

<%@ page pageEncoding="UTF-8" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

  (2)修改form標簽

<form:form method="post" id="fm1" commandName="${commandName}" htmlEscape="true" class="sui-form">
......
</form:form>

  (3)修改用戶名框

<form:input id="username" tabindex="1" 
    accesskey="${userNameAccessKey}" path="username" autocomplete="off" htmlEscape="true" 
    placeholder="郵箱/用戶名/手機號" class="span2 input-xfat" />

  (4)修改密碼框

 <form:password  id="password" tabindex="2" path="password" 
      accesskey="${passwordAccessKey}" htmlEscape="true" autocomplete="off" 
      placeholder="請輸入密碼" class="span2 input-xfat"   />

  (5)修改登陸按鈕

<input type="hidden" name="lt" value="${loginTicket}" />
<input type="hidden" name="execution" value="${flowExecutionKey}" />
<input type="hidden" name="_eventId" value="submit" />
<input class="sui-btn btn-block btn-xlarge btn-danger" accesskey="l" value="登陸" type="submit" />

  修改后效果如下:

  

6.2 錯誤提示

  在表單內加入錯誤提示框

<form:errors path="*" id="msg" cssClass="errors" element="div" htmlEscape="false" />

  測試:輸入錯誤的用戶名和密碼,提示是英文:

  

  這個提示信息是在WEB-INF\classes目錄下的messages.properties文件中

authenticationFailure.AccountNotFoundException=Invalid credentials.
authenticationFailure.FailedLoginException=Invalid credentials.

  設置國際化為zn_CN  ,修改cas-servlet.xml

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" p:defaultLocale="zh_CN" />

  我們需要將此信息拷貝到messages_zh_CN.properties下,並改為中文提示(轉為Unicode編碼)

authenticationFailure.AccountNotFoundException=\u7528\u6237\u4E0D\u5B58\u5728.
authenticationFailure.FailedLoginException=\u5BC6\u7801\u9519\u8BEF.

  第一個是用戶名不存在時的錯誤提示

  第二個是密碼錯誤的提示

   

七、CAS客戶端與SpringSecurity集成

7.1 Spring Security測試工程搭建

   (1)建立Maven項目casclient_demo3(war) ,引入spring依賴和spring secrity 相關依賴 ,tomcat端口設置為9003

 <properties>
        <spring.version>4.2.4.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.1.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.1.0.RELEASE</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <!-- java編譯插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <configuration>
                    <!-- 指定端口 -->
                    <port>9003</port>
                    <!-- 請求路徑 -->
                    <path>/</path>
                </configuration>
            </plugin>
        </plugins>
    </build>

  (2)建立web.xml ,添加過濾器等配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-security.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

  (3)創建配置文件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">

    <!--以下頁面不攔截-->
    <http pattern="/login.html" security="none"></http>
    <http pattern="/login_error.html" security="none"></http>

    <!-- 頁面攔截規則,use-expressions:是否啟動SPEL表達式 默認是true -->
    <http use-expressions="false">
        <!-- 當前用戶必須有ROLE_USER的角色 才可以訪問根目錄及所屬子目錄的資源
                /*  表示的是該目錄下的資源,只包括本級目錄不包括下級目錄
                /** 表示的是該目錄以及該目錄下所有級別子目錄的資源
        -->
        <intercept-url pattern="/**" access="ROLE_USER" />
        <!--開啟表單登陸-->
        <!--login-page:指定登錄頁面
            default-target-url:指定了成功進行身份驗證和授權后默認呈現給用戶的頁面。
            authentication-failure-url:指定了身份驗證失敗時跳轉到的頁面。
        -->
        <form-login login-page="/login.html" default-target-url="/index.html" authentication-failure-url="/login_error.html"/>
        <!--csrf disabled="true",關閉csrf -->
        <csrf disabled="true"/>
    </http>

    <!-- 認證管理器 -->
    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="admin" password="123456" authorities="ROLE_USER"/>
            </user-service>
        </authentication-provider>
    </authentication-manager>
</beans:beans>

  (4)添加html頁面(詳細見Spring Security 入門

  

7.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表示放在指定的位置之后(Spring Security 內置過濾器表)  -->
        <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 {
        System.out.println("經過認證類:" + username);
        //構建角色集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        //這個類在此處的作用不是認證,因此password的參數可以為""
        return new User(username, "", authorities);
    }
}

  注意:這個類在此處的作用不是認證,CAS在認證返回來的時候才調用這個類的方法,即這個類在執行這個方法的時候已經是通過認證了。它的主要作用是:登陸后得到用戶名,根據用戶名查詢角色列表或執行一些邏輯。

7.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

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
   
   
    <context:component-scan base-package="cn.itcast.demo" />
    <mvc:annotation-driven />    

</beans>

  (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 即可在控制台看到輸出的登錄名。

7.4 退出登錄

  修改spring-security.xml  

  

  在頁面上添加鏈接

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

  創建index2.html,將index2.html設置為可匿名訪問

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM