<cas-client.version>2.3.0-GA</cas-client.version>
<dependency>
<groupId>net.unicon.cas</groupId>
<artifactId>cas-client-autoconfig-support</artifactId>
<version>${cas-client.version}</version>
</dependency>
引入spring-security-cas
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
</dependency>
spring-security-cas中包含spring security依赖和cas-client-core依赖
如果不想用spring security想用shiro,可以只引入cas-client-core依赖,再引入需要用到的shiro依赖
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<scope>compile</scope>
<version>3.6.1</version>
</dependency>
添加如下配置,设置cas地址,cas登录地址,客户端的访问路径,认证类型
cas:
server-url-prefix: http://localhost:8022/cas
server-login-url: http://localhost:8022/cas/login
client-host-url: http://1.long1.com:8081
validation-type: cas3
spring boot启动类添加注解
@EnableCasClient
新建controller
package com.xdny.sso.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
public class IndexController {
@RequestMapping("/index")
public ModelAndView root(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
return modelAndView;
}
@RequestMapping("/logout")
public void logout (HttpServletResponse response) throws IOException {
// 清理系统session
response.sendRedirect("http://localhost:8022/cas/logout");
}
}
这里使用thymeleaf做测试,引入thymeleaf以及web依赖依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
页面代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<font th:text="${session._const_cas_assertion_.principal.name}"></font><br>
<a href="http://2.long2.com:8082" target="_blank">服务2</a>
<a href="http://3.long3.com:8083" target="_blank">服务3</a>
<a href="/logout">安全退出</a>
</body>
</html>
启动代码后就会跳到我们cas的登录页面了
html页面通过session.const_cas_assertion.principal.name可以访问到当前登录的用户名
这里是因为cas-client-core包下,有一个AbstractTicketValidationFilter再doFilter中设置了当前用户
我们再这个filter中打一个断点,然后去登录cas就会发现,登录成功后,会回调我们配置的客户端地址,并携带了一个ticket属性,然后这个过滤器根据ticket去验证ticket的有效性,并返回登录的用户名
这里我们直接回调了后台服务,后台的过滤器帮我们验证了ticket,再项目开发中,通常采用前后端分离,我们可以直接回调前端地址(后端项目就不再引入cas的jar包及相关依赖了),然后前端拿到ticket后,去调用后端请求服务调用接口验证cas
示例代码如下
官方给的单点登录流程