• CAS客户端与SpringSecurity集成


    4. CAS客户端与SpringSecurity集成

    4.1 Spring Security测试工程搭建

    1)建立Maven项目casclient_demo3 ,引入spring依赖和spring secrity 相关依赖 ,tomcat端口设置为9003

    2)建立web.xml ,添加过滤器等配置

    3)创建配置文件spring-security.xml

    4)添加html页面

    4.2 Spring SecurityCAS集成

    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  

    /**

     * 认证类

     */

    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);

    }

    }

    这个类的主要作用是在登陆后得到用户名,可以根据用户名查询角色或执行一些逻辑。

    4.3获取登录名

    我们在处理后端逻辑需要获得登录名,那么如何获取单点登录的用户名呢? 其实和我们之前获得用户名的方式是完全相同的,我们下面来做个测试。

    1web.xml 添加springmvc

      <servlet>

       <servlet-name>springmvc</servlet-name>

       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

       <!-- 指定加载的配置文件 ,通过参数contextConfigLocation加载-->

       <init-param>

       <param-name>contextConfigLocation</param-name>

       <param-value>classpath:springmvc.xml</param-value>

       </init-param>

      </servlet>

      

      <servlet-mapping>

       <servlet-name>springmvc</servlet-name>

       <url-pattern>*.do</url-pattern>

      </servlet-mapping>

    2)创建springmvc.xml

    <context:component-scan base-package="cn.itcast.demo" />

    <mvc:annotation-driven />

    3)创建UserController  

    @RestController

    public class UserController {

    @RequestMapping("/findLoginUser")

    public void  findLoginUser(){

    String name = SecurityContextHolder.getContext().getAuthentication().getName();

    System.out.println(name);

    }

    }

    地址栏输入http://localhost:9003/findLoginUser.do 即可在控制台看到输出的登录名。

    4.4退出登录

    修改spring-security.xml  

    <beans:bean id="requestSingleLogoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">  

            <beans:constructor-arg value="http://localhost:9100/cas/logout?service=http://localhost:9003/index2.html"/>  

            <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>

    在页面上添加链接

    <a href="/logout/cas">退出登录</a>

    创建index2.html,index2.html设置为可匿名访问

    <http pattern="/index2.html" security="none"></http>

    5.品优购用户中心

    5.1需求分析

    用户中心实现单点登录。

    5.2代码实现

    5.2.1用户中心实现单点登录

    (1)将用户中心相关的页面(home-开头的)拷贝至  pinnyougou-user-web  

     

    2pom.xml 引入springSecuritycas客户端和springSecurity Cas整合包依赖(参照casclient_demo3)。

    3web.xml  添加spring-security过滤器(参照参照casclient_demo3)设置首页为home-index.html

    <welcome-file-list>

    <welcome-file>home-index.html</welcome-file>

    </welcome-file-list>

    4)构建UserDetailsServiceImpl.java  (参照casclient_demo3

     

    (5)添加spring-security.xml(参照casclient_demo3),并做以下修改

    配置匿名访问资源

    <!-- 匿名访问资源 -->

    <http pattern="/css/**" security="none"></http>

    <http pattern="/js/**" security="none"></http>

    <http pattern="/image/**" 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>

    设置服务地址属性

    <beans:bean id="serviceProperties" class="org.springframework.security.cas.ServiceProperties">    

         <beans:property name="service" value="http://localhost:9106/login/cas"/>

    </beans:bean>  

    设置认证类

    <beans:bean

    id="userDetailsService" class="com.pinyougou.user.service.UserDetailServiceImpl"/>  

    5.2.2页面显示用户名

    1pinyougou-user-web创建LoginController.java

    @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;

    }

    );

    }

    });

    5)修改home-index.html  引入js

        <script type="text/javascript" src="plugins/angularjs/angular.min.js"></script>

    <script type="text/javascript" src="js/base.js"></script>

    <script type="text/javascript" src="js/service/loginService.js"></script>

    <script type="text/javascript" src="js/controller/indexController.js"></script>

    指令,调用方法查询登陆名

    <body ng-app="pinyougou" ng-controller="indexController" ng-init="showName()">

    显示用户名

     <span class="name">{{loginName}}</span>

    5.2.3退出登录

    设置退出登录后的跳转地址

    <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:bean>  

    退出登录后,跳转到网站首页

    <span class="safe"> <a href="/logout/cas">退出登录 </a></span>

    附录A. Spring Security 内置过滤器表

    别名

    Filter

    CHANNEL_FILTER

    ChannelProcessingFilter

    SECURITY_CONTEXT_FILTER

    SecurityContextPersistenceFilter

    CONCURRENT_SESSION_FILTER

    ConcurrentSessionFilter

    LOGOUT_FILTER

    LogoutFilter

    X509_FILTER

    X509AuthenticationFilter

    PRE_AUTH_FILTER

    AstractPreAuthenticatedProcessingFilter 的子类

    CAS_FILTER

    CasAuthenticationFilter

    FORM_LOGIN_FILTER

    UsernamePasswordAuthenticationFilter

    BASIC_AUTH_FILTER

    BasicAuthenticationFilter

    SERVLET_API_SUPPORT_FILTER

    SecurityContextHolderAwareRequestFilter

    JAAS_API_SUPPORT_FILTER

    JaasApiIntegrationFilter

    REMEMBER_ME_FILTER

    RememberMeAuthenticationFilter

    ANONYMOUS_FILTER

    AnonymousAuthenticationFilter

    SESSION_MANAGEMENT_FILTER

    SessionManagementFilter

    EXCEPTION_TRANSLATION_FILTER

    ExceptionTranslationFilter

    FILTER_SECURITY_INTERCEPTOR

    FilterSecurityInterceptor

    SWITCH_USER_FILTER

    SwitchUserFilter

    完毕,good luck!

  • 相关阅读:
    javascript获取当前日期、年份和月份等
    程序员也可以懂一点期望值管理
    数据类型,隐式转换以及json,对象,引用类型,预解析 视频教程
    两个值交互位置的几种方法
    通过Class获取标签,兼容的几种思路
    前端开发流程
    元素多层嵌套,JS获取问题
    原生JS实现分页效果2.0(新增了上一页和下一页,添加当前元素样式)
    原生JS实现分页效果1.0
    学习方法,以及时间的安排。
  • 原文地址:https://www.cnblogs.com/hxun/p/11433981.html
Copyright © 2020-2023  润新知