1. 程式人生 > >品優購專案記錄:day15

品優購專案記錄:day15

今日目標:

(1)搭建單點登入服務端,開發單點登入客戶端

(2)實現CAS認證資料來源設定

(3)更換CAS登入頁面

(4)掌握CAS與Spring Security整合

(5)完成使用者中心單點登入功能

目錄

1、品優購使用者中心

1.1 需求分析

使用者中心實現單點登入。

1.2 單點登入

(1)複製靜態資源到user-web工程中(所有home開頭的頁面)

(2)引入依賴(spring security、CAS客戶端、前兩者的整合包)

        <!-- Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
        <!-- Spring Security整合CAS -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-cas</artifactId>
        </dependency>
        <!-- CAS客戶端 -->
        <dependency>
            <groupId>org.jasig.cas.client</groupId>
            <artifactId>cas-client-core</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>log4j-over-slf4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

(3)在web.xml中新增Spring Security的過濾器,放在springmvc的servlet上面

  	 <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/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>

(4)編寫認證類

package com.pinyougou.user.service;

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;

/**
 * 認證類
 * 注意:因為和CAS整合,所以這個類不會有認證賬號密碼的邏輯。
 * Author xushuai
 * Description
 */
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);
    }
}

(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="/register.html" security="none" />
    <http pattern="/user/add.do" security="none" />
    <!-- 放行獲取簡訊驗證碼 -->
    <http pattern="/user/sendCode.do" security="none" />

    <!-- 放行靜態資源 -->
    <http pattern="/css/**" security="none" />
    <http pattern="/img/**" security="none" />
    <http pattern="/js/**" security="none" />
    <http pattern="/plugins/**" security="none" />

	<!--   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:9105/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.pinyougou.user.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>

1.3 顯示當前登入使用者名稱

(1)後端:新建LoginController

package com.pinyougou.user;

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;

/**
 * 登入相關控制層
 * Author xushuai
 * Description
 */
@RestController
@RequestMapping("/login")
public class LoginController {


    /**
     * 獲取當前登入使用者名稱
     *
     * @param
     * @return java.util.Map
     */
    @RequestMapping("/showName")
    public Map showName() {
        Map<String, String> resultMap = new HashMap<>();
        // 獲取當前登入使用者名稱
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        // 放入結果集
        resultMap.put("loginName", username);

        return resultMap;
    }
}

注意:我這裡的service和controller包是同級別的包,但是我的包掃描是controller,所以需要修改包掃描路徑

(2)前端:新建loginService.js

//服務層
app.service('loginService',function($http){
    // 獲取當前登入使用者名稱
    this.showName = function () {
        return $http.get('../login/showName.do');
    }
});

(3)前端:新建indexController.js

//控制層
app.controller('indexController' ,function($scope,$controller,loginService){

    // 展示當前登入使用者名稱
    $scope.showName = function () {
        loginService.showName().success(
            function (rtn) {
                $scope.loginName = rtn.loginName;
            }
        );
    }
    
}

(4)前端:頁面引入JS檔案和基礎指令以及頁面繫結變數

(5)測試

1.4 單點退出

(1)修改退出登入的連結地址

(2)修改spring-security.xml中的單點退出配置