单点登录框架 CAS(Security)+springmvc

  • Post author:
  • Post category:其他




单点登录框架 CAS(Security)



1. 单点登录

单点登录(Single Sign On),简称为 SSO,是目前比较流行的企业业务整合的解决方案之一。SSO 的定义是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统。

image.png



2.CAS



CAS 具有以下特点:

【1】开源的企业级单点登录解决方案。

【2】CAS Server 为需要独立部署的 Web 应用。

【3】CAS Client 支持非常多的客户端(这里指单点登录系统中的各个 Web 应用),包括Java, .Net, PHP, Perl, Apache, uPortal, Ruby 等。



CAS 包含两个部分:

CAS Server 和 CAS Client。CAS Server 需要独立部署,主要负责对用户的认证工作;CAS Client 负责处理对客户端受保护资源的访问请求,需要登录时,重定向到 CAS Server。

image.png


CAS单点登录流程图.png


security整合改动代码1-认证.jpg


security整合改动代码2-认证.jpg


security整合改动代码3-认证.jpg


开发配置的点.jpg



3.SSO 单点登录访问流程主要有以下步骤:

  1. 访问服务:SSO 客户端发送请求访问应用系统提供的服务资源。

    2. 定向认证:SSO 客户端会重定向用户请求到 SSO 服务器。

    3. 用户认证:用户身份认证。

    4. 发放票据:SSO 服务器会产生一个随机的 Service Ticket。

    5. 验证票据:SSO 服务器验证票据 Service Ticket 的合法性,验证通过后,允许客户端访问服务。

    6. 传输用户信息:SSO 服务器验证票据通过后,传输用户认证结果信息给客户端。



4.CAS部署



4.1CAS服务端部署



4.1.1端口修改

如果我们不希望用 8080 端口访问 CAS, 可以修改端口



(1)修改 TOMCAT 的端口

打开 tomcat 目录 conf\server.xml 找到下面的配置

image.png



(2)修改 CAS 配置文件

修改 cas 的 WEB-INF/cas.properties

server.name=http://localhost:9100



4.1.2去除 https  认证

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

这里需要增加参数 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



5.客户端



5.1创建maven(war)工程



5.2引入依赖

<!-- cas -->
<dependency>
  <groupId>org.jasig.cas.client</groupId>
  <artifactId>cas-client-core</artifactId>
  <version>3.3.3</version>
</dependency>



5.3web.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:9100/cas/login</param-value>
    <!--这里的 server 是服务端的 IP -->
    </init-param>
    <init-param>
      <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:9100/cas</param-value>
    </init-param>
    <init-param>
      <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>



5.4获取登录用户名

request.getRemoteUser()为获取远程登录名(jsp页面)



6.单点退出登录功能



6.1路径:http://localhost:9100/cas/logout



6.2服务端(退出登录后,能自动跳转到某个页面)



6.2.1修改 cas 系统的配置文件 cas-servlet.xml

<bean id="logoutAction" class="org.jasig.cas.web.flow.LogoutAction"
  p:servicesManager-ref="servicesManager"
  p:followServiceRedirects="${cas.logout.followServiceRedirects:true}"/>

可以在退出时跳转页面到目标页面,修改 index.jsp 的退出链接


退出登录



7.服务端数据源



7.1配置数据源



7.1.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” />

//默认cas密码加密方式

//自定义加密方式


https://blog.csdn.net/sz85850597/article/details/78469735


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

找到配置进行注释

添加配置

image.png



8.服务端界面改造



8.1资源拷贝



8.1.1将自身项目的登录界面拷贝到 cas 系统下 WEB-INF\view\jsp\default\ui 目录下



8.1.2相关静态资源拷贝到cas目录下



8.1.3将原来的 casLoginView.jsp 改名(可以为之后的修改操作做参照),将 login.html 改名为 casLoginView.jsp



8.2修改页面(自身项目修改名字的页面)



8.2.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" %>



8.2.2修改from标签

<form:form method="post" id="fm1" commandName="${commandName}" htmlEscape="true"
class="sui-form">
......
  <!--将自身登陆表单项的from进行更改/或把自身提交信息表单被包围-->
</form:form>





8.2.3修改用户名框(表单项)

<form:input id="username" tabindex="1"
  accesskey="${userNameAccessKey}" path="username" autocomplete="off" htmlEscape="true"
 	<!--下面一行为原页面属性-->
  placeholder="邮箱/用户名/手机号" class="span2 input-xfat" />



8.2.4修改密码框

<form:password id="password" tabindex="2" path="password"
  accesskey="${passwordAccessKey}" htmlEscape="true" autocomplete="off"
               <!--下面一行为原页面属性-->
  placeholder="请输入密码" class="span2 input-xfat" />



8.2.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" />



8.2.6错误提示

表单内加入错误提示框
<form:errors path="*" id="msg" cssClass="errors" element="div" htmlEscape="false" />

修改 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客户端与Security集成



1.Spring Security工程创建



(1)建立 Maven 项目,引入 spring 依赖和 spring secrity 相关依赖

    <properties>
        <spring.version>4.2.4.RELEASE</spring.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

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



(2)建立 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">
    <!-- 加载spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:spring/spring-security.xml</param-value>
    </context-param>
    <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>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>



(3)创建文件 spring-security.xml



(4)添加 html 页面



2.引入依赖

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



3.修改 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="/index2.html" 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">
        <!--配置自身工程的根地址+/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="com.wsp.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?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>
    <!-- 单点登出  结束 -->

</beans:beans>



4.创建 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);
    }
}



5.获取登录名



5.1web.xml 添加 springmvc修改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">

    <!-- 加载spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:spring/spring-security.xml</param-value>
    </context-param>
    <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>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

<!--============================下面为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:spring/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

</web-app>



5.2创建springmvc文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.wsp.demo.controller"/>
    <mvc:annotation-driven/>
</beans>



5.3创建 UserController

地址栏输入web工程地址+资源路径 即可在控制台看到输出的登录名。

@RestController
public class UserController {
  @RequestMapping("/findLoginUser")
  public void findLoginUser(){
    String name =
    SecurityContextHolder.getContext().getAuthentication().getName();
    System.out.println(name);
  } 
}



6.退出登录(Security中已配置)

<!--页面添加链接-->
<a href="/logout/cas">退出登录</a>



版权声明:本文为weixin_45094738原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。