cas单点登陆。就这一篇就够了!!!!!
前言:
cas是什么我就不累贅說了。就簡單說下大致的流程。首先,cas是一個獨立的項目。就是一個war包,部署在tomcat上面啟動就ok。然后我們要實現單點登陸,無疑是訪問系統1,如果沒有登錄,就跳轉到cas服務器上面,然后進行登陸,登陸ok之后,又從cas服務跳轉到系統1的界面,然后訪問系統2的時候,直接就可以訪問了,不用再次登陸。你要問如何實現各種跳轉呢?那就需要我們在cas服務上和我們的子系統上面做出相應的配置的就ok。不用寫代碼。很爽有木有。
修改cas的https為http
CAS默認使用的是HTTPS協議,如果使用HTTPS協議需要SSL安全證書(需向特定的機構申請和購買) 。如果對安全要求不高或是在開發測試階段,可使用HTTP協議。我們這里講解通過修改配置,讓CAS使用HTTP協議。
?
(1)修改cas的WEB-INF/deployerConfigContext.xml??
找到下面的配置
<bean class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler" p:httpClient-ref="httpClient"/>這里需要增加參數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="true"p:cookieMaxAge="-1"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="true" p:cookieMaxAge="-1" p:cookieName="CASPRIVACY" p:cookiePath="/cas" />我們這里將cookieSecure改為false , ?cookieMaxAge?改為3600
?
例子
你可以建兩個maven的web項目,只需要修改web.xml和pom.xml即可。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>cn.itcast.demo</groupId><artifactId>casclient_demo1</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><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></project>?
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:9080/cas/login</param-value><!--這里的server是服務端的IP --> </init-param> <init-param><!--當前項目的url地址--><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:9080/cas</param-value></init-param> <init-param><!--當前項目的url地址--><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>單點退出登錄
地址欄輸入 ?http://localhost:9100/cas/logout?
但我們更希望退出登錄后,能自動跳轉到某個頁面,那如何處理呢?
修改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 ,添加如下配置
?
<!-- c3p0連接數據庫 --> <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 id="authenticationManager" class="org.jasig.cas.authentication.PolicyBasedAuthenticationManager"><constructor-arg><map> <entry key-ref="proxyAuthenticationHandler" value-ref="proxyPrincipalResolver" /><entry key-ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" /></map></constructor-arg> <property name="authenticationPolicy"><bean class="org.jasig.cas.authentication.AnyAuthenticationPolicy" /></property> </bean>其中
<entry key-ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" />一句是使用固定的用戶名和密碼,我們在下面可以看到這兩個bean ,如果我們使用數據庫認證用戶名和密碼,需要將這句注釋掉。
添加下面這一句配置
<entry key-ref="dbAuthHandler" value-ref="primaryPrincipalResolver"/>(3)將以下三個jar包放入webapps\cas\WEB-INF\lib下
?
?
CAS服務端界面改造
?
(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" />錯誤提示
在表單內加入錯誤提示框
<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下,并改為中文提示(轉碼)
?
authenticationFailure.AccountNotFoundException=\u7528\u6237\u4E0D\u5B58\u5728. authenticationFailure.FailedLoginException=\u5BC6\u7801\u9519\u8BEF.?
CAS客戶端與SpringSecurity集成
?
(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.xsdhttp://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? ? ? 其實是馬后炮,因為認證的功能cas提前認證過了,他的作用只是得到用戶權限返回。
/*** 認證類*/ public class UserDetailServiceImpl implements UserDetailsService {@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {//構建角色集合List<GrantedAuthority> authorities=new ArrayList();authorities.add(new SimpleGrantedAuthority("ROLE_USER"));return new User(username, "" , authorities); } }這個類的主要作用是在登陸后得到用戶名,可以根據用戶名查詢角色或執行一些邏輯。
轉載于:https://www.cnblogs.com/coder-lzh/p/9222467.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的cas单点登陆。就这一篇就够了!!!!!的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 无法再关联PayPal账户,但此前已关联
- 下一篇: MySQL慢查询(一) - 开启慢查询