cas單點登錄。就這一篇就夠了!!!!!

前言:

cas是什麼我就不累贅說了。就簡單說下大體的流程。首先,cas是一個獨立的項目。就是一個war包,部署在tomcat上面啓動就ok。而後咱們要實現單點登錄,無疑是訪問系統1,若是沒有登陸,就跳轉到cas服務器上面,而後進行登錄,登錄ok以後,又從cas服務跳轉到系統1的界面,而後訪問系統2的時候,直接就能夠訪問了,不用再次登錄。你要問如何實現各類跳轉呢?那就須要咱們在cas服務上和咱們的子系統上面作出相應的配置的就ok。不用寫代碼。很爽有木有。css

修改cas的https爲http

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

 

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

找到下面的配置mysql

<bean class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"
p:httpClient-ref="httpClient"/>

這裏須要增長參數p:requireSecure="false"requireSecure屬性意思爲是否須要安全驗證,即HTTPSfalse爲不採web

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

找到下面配置sql

<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秒內,打開任意窗口,都不須要驗證。express

咱們這裏將cookieSecure改成false ,  cookieMaxAge 改成3600apache

(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-infdeployerConfigContext.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.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      實際上是馬後炮,由於認證的功能cas提早認證過了,他的做用只是獲得用戶權限返回。

/**
 * 認證類
 */
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);        
    }
}

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

相關文章
相關標籤/搜索