0
点赞
收藏
分享

微信扫一扫

Spring Security整合CAS单点登录(一)

西特张 2021-10-04 阅读 66
权限系统

什么是单点登录?单点登录全称Single Sign On(以下简称SSO),是指在多系统应用群中登录一个系统,便可在其他所有系统中得到授权而无需再次登录,包括单点登录单点注销两部分。

1、单点登录流程

单点登录流程较为复杂,首先先明确流程中,登录的处理一定是由SSO认证中心来做,但是访问的资源存在于各个系统中。所以SSO认证中心必须授权给系统,用户才可以访问资源,这里就用到了令牌和全局/局部会话的技术,我们来看流程图:


系统1

  1. 用户通过浏览器访问系统1,系统1发现局部会话(系统1自身的会话)不存在,此时会发起跳转到SSO认证中心并携带系统1的地址,SSO认证中心发现全局会话也不存在,就会进入登录流程,返回登陆页面给浏览器,辞此时系统1的地址携带在登录地址中。
  2. 用户在浏览器输入用户名和密码以及携带系统1的地址(注意这个地址在返回登陆页面的时候就已经存在了),SSO认证中心验证用户名和密码,一旦成功就会创建全局会话(多个系统可以共享的会话)和授权令牌。认证中心根据携带的系统1的地址,跳转到系统1,并携带令牌。
  3. 系统1获取到令牌之后,需要去校验令牌的合法性,系统1的后端发送请求到认证中心并携带授权令牌系统1的地址。认证中心校验令牌有效,将系统1的地址注册到本地并标识合法,并通知系统1令牌有效。
  4. 系统1创建局部会话(需要存储令牌),允许用户访问受保护的资源。

系统2

  1. 用户通过浏览器访问系统2,系统2发现局部会话(系统2自身的会话)不存在,此时会发起跳转到SSO认证中心,SSO认证中心发现全局会话存在,就直接颁发授权令牌给系统2。
  2. 系统2执行系统1的步骤3和4。

2、单点注销流程

单点登录自然也要单点注销,在一个子系统中注销,所有子系统的会话都将被销毁,用下面的图来说明:


  1. 系统1接收注销请求,取出会话中的令牌,发送请求到SSO认证中心。
  2. SSO认证中心校验令牌有效性,如果一旦发现有效就销毁全局会话,并通知所有相关注册的系统进行销毁,通知时要携带对应系统的令牌。
  3. 各个系统接收到令牌之后,销毁局部会话,SSO认证中心将用户的请求重定向到登录页面。

3、CAS介绍

SSO 仅仅是一种设计,而 CAS 则是实现 SSO 的一种手段。CAS (Central Authentication Service)中心授权服务,本身是一个开源协议,分为 1.0 版本和 2.0 版本。1.0 称为基础模式,2.0称为代理模式,适用于存在非 Web 应用之间的单点登录,本文只涉及 CAS 1.0。


可以看到CAS的流程与上文中的SSO一致,我们来看下CAS中令牌(票据)的概念:

TGT:Ticket Grangting Ticket
TGT 是 CAS 为用户签发的登录票据,拥有了 TGT,用户就可以证明自己在 CAS 成功登录过。TGT 封装了 Cookie 值以及此 Cookie 值对应的用户信息。当 HTTP 请求到来时,CAS 以此 Cookie 值(TGC)为 key 查询缓存中有无 TGT ,如果有的话,则相信用户已登录过。

TGC:Ticket Granting Cookie
CAS Server 生成TGT放入自己的 Session 中,而 TGC 就是这个 Session 的唯一标识(SessionId),以 Cookie 形式放到浏览器端,是 CAS Server 用来明确用户身份的凭证。

ST:Service Ticket
ST 是 CAS 为用户签发的访问某一 service 的票据。用户访问 service 时,service 发现用户没有 ST,则要求用户去 CAS 获取 ST。用户向 CAS 发出获取 ST 的请求,CAS 发现用户有 TGT,则签发一个 ST,返回给用户。用户拿着 ST 去访问 service,service 拿 ST 去 CAS 验证,验证通过后,允许用户访问资源。

4、CAS环境搭建

下载CAS5.3的版本,具体构建war包过程略过,大家可以自行网上搜索。我已经把war包上传到网盘中,下载地址:

链接:https://pan.baidu.com/s/1som_l_eFONrDOZzuv2JXDQ 
提取码:4zti 

将war包部署到tomcat下进行启动,访问地址:http://localhost:8880/cas/login。8880是我tomcat的端口号,请自行修改。
如果出现如下的页面,CAS启动成功:

4.1 修改配置

打开cas-server-webapp下的resources/services下的HTTPSandIMAPS-10000001.json文件,修改内容为:

{
  "@class" : "org.apereo.cas.services.RegexRegisteredService",
  "serviceId" : "^(https|imaps|http)://.*",
  "name" : "HTTPS and IMAPS",
  "id" : 10000001,
  "description" : "This service definition authorizes all application urls that support HTTPS and IMAPS protocols.",
  "evaluationOrder" : 10000
}

支持http的访问方式。
修改WEB-INF\classes\application.properties文件,在最后追加内容:

cas.tgc.secure=false
cas.serviceRegistry.initFromJson=true

同时我们发现,cas默认登录账号密码为:

cas.authn.accept.users=casuser::Mellon

4.2 搭建spring boot + spring security cas环境

创建spring boot项目(略)
添加依赖,如下:

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-cas</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

创建引导类:

package com.itheima.authspringsecuritycasservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@SpringBootApplication
//开启spring security过滤器链
@EnableWebSecurity
public class AuthSpringSecurityCasServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(AuthSpringSecurityCasServiceApplication.class, args);
    }

}

添加cas配置类:

package com.itheima.authspringsecuritycasservice.config;

import org.jasig.cas.client.session.SingleSignOutFilter;
import org.jasig.cas.client.validation.Cas30ServiceTicketValidator;
import org.jasig.cas.client.validation.TicketValidator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;

@Configuration
public class CasConfig {

    @Value("${cas.server.url}")
    private String casServerUrl;
    @Value("${base.url}")
    private String baseUrl;

    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint();
        entryPoint.setLoginUrl(casServerUrl + "/login");
        entryPoint.setServiceProperties(this.serviceProperties());
        return entryPoint;
    }

    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return new ProviderManager(this.casAuthenticationProvider());
    }

    @Bean
    public CasAuthenticationFilter casAuthenticationFilter(
            AuthenticationManager authenticationManager,
            ServiceProperties serviceProperties) throws Exception {
        CasAuthenticationFilter filter = new CasAuthenticationFilter();
        filter.setAuthenticationManager(authenticationManager);
        filter.setServiceProperties(serviceProperties);
        return filter;
    }

    @Bean
    public ServiceProperties serviceProperties() {
        ServiceProperties serviceProperties = new ServiceProperties();
        serviceProperties.setService(baseUrl + "/login/cas");
        serviceProperties.setSendRenew(false);
        return serviceProperties;
    }

    @Bean
    public TicketValidator ticketValidator() {
        return new Cas30ServiceTicketValidator(casServerUrl);
    }

    @Bean
    public CasAuthenticationProvider casAuthenticationProvider() {
        CasAuthenticationProvider provider = new CasAuthenticationProvider();
        provider.setServiceProperties(this.serviceProperties());
        provider.setTicketValidator(this.ticketValidator());
        provider.setUserDetailsService(new CustomUserDetailsService());
        provider.setKey("CAS_PROVIDER_LOCALHOST");
        return provider;
    }

    @Bean
    public SecurityContextLogoutHandler securityContextLogoutHandler() {
        return new SecurityContextLogoutHandler();
    }

    @Bean
    public LogoutFilter logoutFilter() {
        LogoutFilter logoutFilter = new LogoutFilter(casServerUrl + "/logout?service=" + baseUrl,
                securityContextLogoutHandler());
        logoutFilter.setFilterProcessesUrl("/logout/cas");
        return logoutFilter;
    }

    @Bean
    public SingleSignOutFilter singleSignOutFilter() {
        SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter();
        singleSignOutFilter.setIgnoreInitConfiguration(true);
        return singleSignOutFilter;
    }
}

自定义用户信息服务类,仅供测试:

package com.itheima.authspringsecuritycasservice.config;

import org.springframework.security.core.authority.AuthorityUtils;
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;

public class CustomUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 可自定义获取用户信息
        return new User("admin", "admin", true, true, true, true,
                AuthorityUtils.createAuthorityList("ROLE_ADMIN"));
    }
}

security配置类:

package com.itheima.authspringsecuritycasservice.config;

import org.jasig.cas.client.session.SingleSignOutFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.logout.LogoutFilter;

@EnableWebSecurity
public class WebConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private SingleSignOutFilter singleSignOutFilter;
    @Autowired
    private LogoutFilter logoutFilter;
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    private CasAuthenticationFilter casAuthenticationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login/cas").permitAll()
                .anyRequest().authenticated()
                .and().httpBasic().authenticationEntryPoint(authenticationEntryPoint)
                .and()
                .addFilter(casAuthenticationFilter)
                .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class)
                .addFilterBefore(logoutFilter, LogoutFilter.class);
    }
}

修改配置文件application.yml

base:
  url: http://localhost:8881
cas:
  server:
    url: http://localhost:8880/cas
server:
  port: 8881

编写controller:

package com.itheima.authspringsecuritycasservice.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping
@RestController
public class WelcomeController {

    @GetMapping("/")
    public String index() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return "当前用户信息:" + auth.getPrincipal();
    }
}

5、测试

启动项目,访问http://localhost:8881,成功跳转到了cas登录页面:


输入账号密码(casuser | Mellon)成功跳转到服务页面:

我们再启动一个服务来测试,添加启动JVM参数:

-Dserver.port=8882 -Dbase.url=http://localhost:8882

访问http://localhost:8882,成功访问:

接下来我们测试一下退出登录,访问localhost:8881/logout/cas:


成功显示注销页面,我们再次访问localhost:8882:



发现无法登录,证明全局会话已经被销毁,测试成功。

举报

相关推荐

0 条评论