cas單點登錄旨在解決傳統登錄模式session在分布式項目中共享登錄信息的問題。
本文cas服務器使用 4.0版本,僅供學習參考。把 cas.war 直接部署在tomcat即可,這里有個固定的用戶名和密碼 casuser /Mellon
修改密碼在 cas/WEB-INF/deployerConfigContext.xml
<bean id="primaryAuthenticationHandler" class="org.jasig.cas.authentication.AcceptUsersAuthenticationHandler"> <property name="users"> <map> <entry key="casuser" value="Mellon"/> <entry key="admin" value="123456"/> </map> </property> </bean>
需要重啟tomcat才能失效
一、 CAS服務端配置
1、端口修改
如果我們不希望用8080端口訪問CAS, 可以修改端口
(1)修改TOMCAT的端口
打開tomcat 目錄 conf\server.xml 找到下面的配置

將端口8080,改為9100
(2)修改CAS配置文件(直接修改tomcat部署的cas)
修改cas的WEB-INF/cas.properties
server.name=http://localhost:9100
2、去除https認證
CAS默認使用的是HTTPS協議,如果使用HTTPS協議需要SSL安全證書(需向特定的機構申請和購買) 。如果對安全要求不高或是在開發測試階段,可使用HTTP協議。我們這里講解通過修改配置,讓CAS使用HTTP協議。
(1)修改cas的WEB-INF/deployerConfigContext.xml
<!-- Required for proxy ticket mechanism. -->
<bean id="proxyAuthenticationHandler"
class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"
p:httpClient-ref="httpClient" p:requireSecure="false"/>
這里需要增加參數p:requireSecure="false",requireSecure屬性意思為是否需要安全驗證,即HTTPS,false為不采用
(2)修改cas的/WEB-INF/spring-configuration/ticketGrantingTicketCookieGenerator.xml
<bean id="ticketGrantingTicketCookieGenerator" class="org.jasig.cas.web.support.CookieRetrievingCookieGenerator" p:cookieSecure="false" p:cookieMaxAge="3600" p:cookieName="CASTGC" p:cookiePath="/cas" />
參數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
<bean id="warnCookieGenerator" class="org.jasig.cas.web.support.CookieRetrievingCookieGenerator" p:cookieSecure="false" p:cookieMaxAge="3600" p:cookieName="CASPRIVACY" p:cookiePath="/cas" />
我們這里將cookieSecure改為false , cookieMaxAge 改為3600
(4)登出跳轉的配置 ,修改 cas 系統的配置文件 cas-servlet.xml
<bean id="logoutAction" class="org.jasig.cas.web.flow.LogoutAction" p:servicesManager-ref="servicesManager" p:followServiceRedirects="${cas.logout.followServiceRedirects:true}"/>
改為 true 后,可以在退出時跳轉頁面到目標頁面,修改 index.jsp 的退出鏈接
<a href="http://localhost:9100/cas/logout?service=http://www.baidu.com">退出登錄</a>
二、CAS集成數據庫
達到用戶登錄從數據庫驗證賬號密碼的目的。
(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="123456" /> <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 authenticationManager 修改
<bean id="authenticationManager" class="org.jasig.cas.authentication.PolicyBasedAuthenticationManager"> <constructor-arg> <map> <!-- | IMPORTANT | Every handler requires a unique name. | If more than one instance of the same handler class is configured, you must explicitly | set its name to something other than its default name (typically the simple class name). --> <entry key-ref="proxyAuthenticationHandler" value-ref="proxyPrincipalResolver" /> <!--<entry key-ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" />--> <entry key-ref="dbAuthHandler" value-ref="primaryPrincipalResolver"/> </map> </constructor-arg>
其中<entry key-ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" />一句是使用固定的用戶名和密碼,我們在下面可以看到這兩個bean ,如果我們使用數據庫認證用戶名和密碼,需要將這句注釋掉。添加<entry key-ref="dbAuthHandler" value-ref="primaryPrincipalResolver"/>使用數據庫數據驗證
(2)將以下三個jar包放入webapps\cas\WEB-INF\lib下

重啟tomcat 登錄

三、CAS服務端界面改造
主要修改cas默認的登錄等頁面,用自己的頁面。
1、拷貝資源
(1)將品優購的登陸頁login.html 拷貝到cas系統下WEB-INF\view\jsp\default\ui 目錄下,將 css 、js、img等文件夾拷貝合並到 cas 目錄下
(2) 將原來的casLoginView.jsp 改名(可以為之后的修改操作做參照),將login.html改名為casLoginView.jsp
2、修改頁面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" />
3、錯誤提示
(1)在表單內加入錯誤提示框
<form:errors path="*" id="msg" cssClass="errors" element="div" htmlEscape="false" />
(2)修改錯誤提示信息為中文
這個提示信息是在WEB-INF\classes目錄下的messages.properties文件中,錯誤信息可以自定義,記得轉成unicode編碼
#用戶不存在,信息可以自定義轉unicode防止中文亂碼 authenticationFailure.AccountNotFoundException=\u7528\u6237\u4E0D\u5B58\u5728 #密碼錯誤同上 authenticationFailure.FailedLoginException=\u5BC6\u7801\u9519\u8BEF
設置國際化為zn_CN ,修改WEB-INF/cas-servlet.xml
<!-- Locale Resolver --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" p:defaultLocale="zh_CN" />

四、CAS客戶端與SpringSecurity集成
1、用戶中心實現單點登錄
(1)pom.xml 引入springSecurity、cas客戶端和springSecurity Cas整合包依賴
<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>
<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)將用戶中心相關的頁面(home-開頭的)拷貝至 pinnyougou-user-web
(3)web.xml 添加spring-security過濾器,設置首頁為home-index.html
<welcome-file-list>
<welcome-file>home-index.html</welcome-file>
</welcome-file-list>
(4)構建UserDetailsServiceImpl.java

import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import java.util.ArrayList; import java.util.List; 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")); return new User(username,"",authorities); } }
(5)添加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="/css/**" security="none"></http> <http pattern="/img/**" security="none"></http> <http pattern="/js/**" 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> <!-- 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:9106/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="com.smallshop.user.service.UserDetailServiceImpl"/> <!-- 認證過濾器 結束 --> <!-- 單點登出 開始 --> <beans:bean id="singleLogoutFilter" class="org.jasig.cas.client.session.SingleSignOutFilter"/> <!-- 經過此配置,當用戶在地址欄輸入本地工程 /logout/cas --> <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: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>
2、頁面顯示用戶名
(1)pinyougou-user-web創建LoginController.java
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @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; } ); } });
(4)修改home-index.html 引入js
<scripttype="text/javascript"src="plugins/angularjs/angular.min.js"></script> <scripttype="text/javascript"src="js/base.js"></script> <scripttype="text/javascript"src="js/service/loginService.js"></script> <scripttype="text/javascript"src="js/controller/indexController.js"></script>
指令,調用方法查詢登陸名
<bodyng-app="pinyougou"ng-controller="indexController"ng-init="showName()">
顯示用戶名
<spanclass="name">{{loginName}}</span>
3、退出登錄
spring-security.xml設置退出登錄后的跳轉地址
<!-- 經過此配置,當用戶在地址欄輸入本地工程 /logout/cas -->
<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:constructor-arg>
<beans:bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
</beans:constructor-arg>
<beans:property name="filterProcessesUrl" value="/logout/cas"/>
</beans:bean>
頁面
<span class="safe"><a href="logout/cas">退出登錄 </a></span>
