cas單點登陸旨在解決傳統登陸模式session在分佈式項目中共享登陸信息的問題。javascript
本文cas服務器使用 4.0版本,僅供學習參考。把 cas.war 直接部署在tomcat便可,這裏有個固定的用戶名和密碼 casuser /Melloncss
修改密碼在 cas/WEB-INF/deployerConfigContext.xmlhtml
<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才能失效java
若是咱們不但願用8080端口訪問CAS, 能夠修改端口mysql
(1)修改TOMCAT的端口angularjs
打開tomcat 目錄 conf\server.xml 找到下面的配置web
將端口8080,改成9100spring
(2)修改CAS配置文件(直接修改tomcat部署的cas)sql
修改cas的WEB-INF/cas.properties數據庫
server.name=http://localhost:9100
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>
達到用戶登陸從數據庫驗證帳號密碼的目的。
(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默認的登陸等頁面,用本身的頁面。
(1)將品優購的登錄頁login.html 拷貝到cas系統下WEB-INF\view\jsp\default\ui 目錄下,將 css 、js、img等文件夾拷貝合併到 cas 目錄下
(2) 將原來的casLoginView.jsp 更名(能夠爲以後的修改操做作參照),將login.html更名爲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" />
(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" />
(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>
(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>
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>