分布式项目单点登录SSO

问题:在分布式开发中,用户登陆的Session共享问题?

1.粘性session
粘性session是指Ngnix每次都将同一用户的所有请求转发至同一台服务器上,即将用户与服务器绑定。
2.服务器session复制
即每次session发生变化时,创建或者修改,就广播给所有集群中的服务器,使所有的服务器上的session相同,不建议使用,因为tomcat节点有数量限制,节点多了,性能反而会下降
3.session共享
缓存session,使用redis, memcached。
4.session持久化
将session存储至数据库中,像操作数据一样才做session。
5.单点登录

1. 什么是单点登录?

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

2. 什么是CAS?

CAS 是 Yale 大学发起的一个开源项目,是对单点登录的一个解决方案,旨在为 Web 应用系统提供一种可靠的单点登录方法,CAS 在 2004 年 12 月正式成为 JA-SIG 的一个项目。CAS 具有以下特点:
分布式项目单点登录SSO_第1张图片
SSO单点登录访问流程主要有以下步骤:
1. 访问服务:SSO客户端发送请求访问应用系统提供的服务资源。
2. 定向认证:SSO客户端会重定向用户请求到SSO服务器。
3. 用户认证:用户身份认证。
4. 发放票据:SSO服务器会产生一个随机的Service Ticket。
5. 验证票据:SSO服务器验证票据Service Ticket的合法性,验证通过后,允许客户端访问服务。
6. 传输用户信息:SSO服务器验证票据通过后,传输用户认证结果信息给客户端。

3.CAS的小Demo

一.配置CAS Server
1) 将cas的war包部署到tomcat中,运行解压
2) 修改tomcat端口
修改tomcat的配置apache-tomcat-cas/conf/server.xml
修改cas项目的的WEB-INF/cas.properties*
server.name=http://localhost:9100
3) 去除https认证
修改cas的WEB-INF/deployerConfigContext.xml

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

cas的/WEB-INF/spring-configuration/ticketGrantingTicketCookieGenerator.xml

id="ticketGrantingTicketCookieGenerator" class="org.jasig.cas.web.support.CookieRetrievingCookieGenerator"
      p:cookieSecure="false"
      p:cookieMaxAge="3600"
      p:cookieName="CASTGC"
      p:cookiePath="/cas" />

修改cas的WEB-INF/spring-configuration/warnCookieGenerator.xml

"warnCookieGenerator" class="org.jasig.cas.web.support.CookieRetrievingCookieGenerator"
p:cookieSecure="false"
p:cookieMaxAge="3600"
p:cookieName="CASPRIVACY"
p:cookiePath="/cas" />

参数p:cookieMaxAge=”-1”,是COOKIE的最大生命周期,-1为无生命周期,即只在当前打开的窗口有效,关闭或重新打开其它窗口,仍会要求验证。可以根据需要修改为大于0的数字,比如3600等,意思是在3600秒内,打开任意窗口,都不需要验证。

二. 配置CAS client
1) 创建web项目,加入maven依赖

<dependencies>
    
    <dependency>
        <groupId>org.jasig.cas.clientgroupId>
        <artifactId>cas-client-coreartifactId>
        <version>3.3.3version>
    dependency>

    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>servlet-apiartifactId>
        <version>2.5version>
        <scope>providedscope>
    dependency>
dependencies>

2) 配置web.xml


<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.SingleSignOutHttpSessionListenerlistener-class>  
    listener>  

      
    <filter>  
        <filter-name>CAS Single Sign Out Filterfilter-name>  
        <filter-class>org.jasig.cas.client.session.SingleSignOutFilterfilter-class>  
    filter>  
    <filter-mapping>  
        <filter-name>CAS Single Sign Out Filterfilter-name>  
        <url-pattern>/*url-pattern>  
    filter-mapping>  

      
    <filter>  
        <filter-name>CASFilterfilter-name>  
        <filter-class>org.jasig.cas.client.authentication.AuthenticationFilterfilter-class>  
        <init-param>  
            <param-name>casServerLoginUrlparam-name>  
            <param-value>http://localhost:9100/cas/loginparam-value>  
              
        init-param>  
        <init-param>  
            <param-name>serverNameparam-name>  
            <param-value>http://localhost:9002param-value>
        init-param>  
    filter>  
    <filter-mapping>  
        <filter-name>CASFilterfilter-name>  
        <url-pattern>/*url-pattern>  
    filter-mapping>  

      
    <filter>  
        <filter-name>CAS Validation Filterfilter-name>  
        <filter-class>  
            org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilterfilter-class>  
        <init-param>  
            <param-name>casServerUrlPrefixparam-name>  
            <param-value>http://localhost:9100/casparam-value>  
        init-param>  
        <init-param>  
            <param-name>serverNameparam-name>  
            <param-value>http://localhost:9002param-value>
        init-param>  
    filter>  
    <filter-mapping>  
        <filter-name>CAS Validation Filterfilter-name>  
        <url-pattern>/*url-pattern>  
    filter-mapping>  

      
    <filter>  
        <filter-name>CAS HttpServletRequest Wrapper Filterfilter-name>  
        <filter-class>  
            org.jasig.cas.client.util.HttpServletRequestWrapperFilterfilter-class>  
    filter>  
    <filter-mapping>  
        <filter-name>CAS HttpServletRequest Wrapper Filterfilter-name>  
        <url-pattern>/*url-pattern>  
    filter-mapping>  

      
    <filter>  
        <filter-name>CAS Assertion Thread Local Filterfilter-name>  
        <filter-class>org.jasig.cas.client.util.AssertionThreadLocalFilterfilter-class>  
    filter>  
    <filter-mapping>  
        <filter-name>CAS Assertion Thread Local Filterfilter-name>  
        <url-pattern>/*url-pattern>  
    filter-mapping>  

      


web-app>

3) 编写一个jsp页面

<title>demo1title>
head>
<body>
 demo1 <%=request.getRemoteUser()%>
body>
html>

4) 访问客户端,输入密码认证即可

当我们访问我们的工程,会被cas的拦截器拦截,跳转到cas项目的登陆页面,输入验证信息,认证成功后,会自动根据web.xml配置的回执路径,跳转回来
三. 单点退出
1) 修改cas系统的配置文件cas-servlet.xml

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

2) 退出之后访问其他页面

<a href="http://localhost:9100/cas/logout?service=http://www.baidu.com">退出登录a>

四.服务端数据源设置(配置自己的数据库)
1) 修改cas服务端中web-inf下deployerConfigContext.xml ,添加如下配置

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" /> 
id="passwordEncoder" 
class="org.jasig.cas.authentication.handler.DefaultPasswordEncoder"  
        c:encodingAlgorithm="MD5"  
        p:characterEncoding="UTF-8" />  
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"/>

2) 替换原来的认证处理器

ref="primaryAuthenticationHandler" value-ref="primaryPrincipalResolver" />
替换成
ref="dbAuthHandler" value-ref="primaryPrincipalResolver" />

3) 添加数据库以及数据源连接器的相关jar包
五. CAS服务端的页面改造
1)将CAS内置的登录页面换成我们的
改成jsp
将includ引入的页面的头拷贝到我们的页面
替换表单 替换class样式
六.错误消息提示

在表单内加入错误提示框

<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

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.
第一个是用户名不存在时的错误提示
第二个是密码错误的提示

3.CAS与Spring Security整合使用

(1).添加maven依赖

<dependency>
    <groupId>org.springframework.securitygroupId>
    <artifactId>spring-security-webartifactId>
dependency>

<dependency>
    <groupId>org.springframework.securitygroupId>
    <artifactId>spring-security-configartifactId>
dependency>

<dependency>
    <groupId>org.springframework.securitygroupId>
    <artifactId>spring-security-casartifactId>
dependency>
<dependency>
    <groupId>org.jasig.cas.clientgroupId>
    <artifactId>cas-client-coreartifactId>
    <exclusions>
        <exclusion>
            <groupId>org.slf4jgroupId>
            <artifactId>log4j-over-slf4jartifactId>
        exclusion>
    exclusions>
dependency>
(2).spring-Security.xml配置

<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="/css/**" security="none">http>
    <http pattern="/img/**" security="none">http>
    <http pattern="/js/**" security="none">http> 
    <http pattern="/plugins/**" security="none">http>
    <http pattern="/fonts/**" security="none">http>
    <http pattern="/cart.html*" security="none">http>


     
    <http use-expressions="false" entry-point-ref="casProcessingFilterEntryPoint">  
        
        <intercept-url pattern="/cart/*.do" access="IS_AUTHENTICATED_ANONYMOUSLY"/>   
        <intercept-url pattern="/**" access="ROLE_USER"/>   
        <csrf disabled="true"/>  
                   
        <custom-filter ref="casAuthenticationFilter"  position="CAS_FILTER" />      
        <custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER"/>  
        <custom-filter ref="singleLogoutFilter" before="CAS_FILTER"/>  
    http>

    
    <beans:bean id="casProcessingFilterEntryPoint" class="org.springframework.security.cas.web.CasAuthenticationEntryPoint">  
          
        <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">  
          
        <beans:property name="service" value="http://localhost:9107/login/cas"/>
    beans:bean>  
    


    
    <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"/>  
        
        <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.cart.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://localhost:9003"/>  
        <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).UserDetailServiceImpl类(空实现,只添加角色即可)
package com.pinyougou.cart.service;

import java.util.ArrayList;
import java.util.List;

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;

/**
 * 认证类
 * 
 * @author Administrator
 *
 */
public class UserDetailServiceImpl implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        List authorities = new ArrayList();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        return new User(username, "", authorities);
    }

}

访问权限控制页面就可跳转到单点登系统了

你可能感兴趣的:(java)