简书未来可能不会更新,来关注我的掘金吧:https://juejin.im/user/5cc2895df265da03a630ddca
。个人博客:http://happyjava.cn
前言
在前面已经介绍过了SSO单点登录的一些理论知识:登录那些事(一):用简单的话来讲讲SSO单点登录。今天我们就通过一个demo来实现下这个CAS系统。
准备工作
建表
CREATE TABLE `users` (
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(255) COLLATE utf8mb4_general_ci NOT NULL,
`password` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
# 插入一条默认数据
INSERT INTO `cas`.`users`(`id`, `username`, `password`) VALUES (1, 'happyjava', '123456');
搭建cas工程
通过Spring initial快速创建一个SpringBoot工程,额外依赖如下:Lombok、MySQL、Mybatis、MybatisPlus、freemarker模板引擎。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
application.propertiees
spring.datasource.url=jdbc:mysql://localhost:3306/cas?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# freeMark config
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
搭建demo工程
简单的一个SpringBoot项目。
CAS系统需要提供如下接口
- 首页请求,如果未登录重定向到登录页面,如果已经登录了,则生成st重定向回业务系统。
/?site=http://server.com:8081
- 登录接口,接受用户输入账号密码的登录请求,登录成功后把用户重定向会业务系统。
POST /login?username=xxx&password=xxx&site=http://server.com:8081
- 校验st接口,提供给业务系统调用校验st是否合法,返回用户信息。
POST /auth?st=XXXX
示例代码如下:(随手demo,只为实现基本功能)
IndexController.java
@Controller
public class IndexController {
/**
* TODO 临时解决方案,真实项目请替换掉。eg:redis、过期时间、过期清理等
*/
private static final Map<String, Integer> ST_MAP = new ConcurrentHashMap<>();
private final UsersMapper usersMapper;
public IndexController(UsersMapper usersMapper) {
this.usersMapper = usersMapper;
}
@RequestMapping(value = {"/"})
public String index(HttpServletRequest request, HttpSession session) {
String site = request.getParameter("site");
if (site == null) {
site = "";
}
Integer userId = (Integer) session.getAttribute("userId");
if (userId != null) {
// 1、登录了
String token = UUID.randomUUID().toString();
ST_MAP.put(token, userId);
if ("".equals(site)) {
// TODO:不考虑找不到user
User user = usersMapper.selectById(userId);
request.setAttribute("username", user.getUsername());
return "index";
} else {
return "redirect:" + site + "/login?st=" + token;
}
} else {
// 2、未登录。重定向到登录界面
request.setAttribute("site", site);
return "login";
}
}
@PostMapping(value = " ")
public String login(String username, String password, String site,
HttpServletRequest request, HttpSession session) {
if (username == null || password == null) {
throw new IllegalArgumentException();
}
List<User> users = usersMapper.selectByMap(new HashMap<>() {{
put("username", username);
put("password", password);
}});
if (users == null || users.size() == 0) {
return "passworderror";
}
User user = users.get(0);
session.setAttribute("userId", user.getId());
String st = UUID.randomUUID().toString();
ST_MAP.put(st, user.getId());
if (site == null || site.equals("")) {
request.setAttribute("username", user.getUsername());
return "redirect:/";
} else {
return String.format("redirect:%s/login?st=%s", site, st);
}
}
@PostMapping(value = "/auth")
@ResponseBody
public Object auth(String st) {
if (st == null || "".equals(st)) {
throw new IllegalArgumentException();
}
Integer userId = ST_MAP.get(st);
if (userId == null) {
return new HashMap<String, Object>() {{
put("result", false);
put("errorMsg", "st异常");
}};
}
User user = usersMapper.selectById(userId);
ST_MAP.remove(st);
return new HashMap<String, Object>() {{
put("result", true);
put("userId", userId);
put("username", user.getUsername());
}};
}
}
页面的代码比较简单,可以查看demo即可。
DEMO业务项目需要提供如下功能
根路径,判断用户是否登陆,未登录则重定向到CAS,已登录则返回正常界面。
接口CAS系统重定向的请求接口,接受st,向CAS请求校验st是否合法,获取用户信息。
GET /login?st=xxx
示例代码如下:(随手demo,只为实现基本功能)
IndexController.java
@Controller
public class IndexController {
private final static String CAS_URL = "http://cas.com:8080";
@Value("${localServerUrl}")
private String localServerUrl;
@GetMapping(value = "/")
public String index(HttpServletRequest request, HttpSession session) {
String username = (String) session.getAttribute("username");
if (username == null || "".equals(username)) {
return String.format("redirect:%s/?site=%s", CAS_URL, localServerUrl);
}
request.setAttribute("username", username);
return "index";
}
@GetMapping(value = "/login")
public String login(String st, HttpServletRequest request) throws JsonProcessingException {
if (st == null || "".equals(st)) {
throw new IllegalArgumentException();
}
RestTemplate restTemplate = new RestTemplate();
String s = restTemplate.postForObject(CAS_URL + "/auth?st=" + st, null, String.class);
ObjectMapper mapper = new ObjectMapper();
ObjectNode result = mapper.readValue(s, ObjectNode.class);
boolean success = result.get("result").asBoolean();
if (!success) {
throw new RuntimeException("st异常");
}
String username = result.get("username").asText();
HttpSession session = request.getSession();
session.setAttribute("username", username);
return "index";
}
}
DEMO配置文件,application.properties
server.port=8081
localServerUrl=http://server.com:${server.port}
# freeMark config
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
测试
为了直观,设置了hosts文件:
127.0.0.1 cas.com
127.0.0.1 server.com
启动CAS,端口:8080。
启动一个demo1,端口:8081。再启动一次demo,端口改为8082:8082
IDEA启动多次项目的设置:
先访问:http://server.com:8081。没有登录server1,被重定向到cas系统登录页。
进行登录:登录成功之后会重定向回到server.com:8081系统上。此时已经完成了第一个系统的登录。
直接访问http://server.com:8082,看看会不会自动登录。
可以看到,先是重定向到cas上,然后cas又重定向回server.com:8082上自动完成登录。
源码下载
如果大家喜欢点个star吧~~~3q。源码下载地址:https://github.com/happyjava007/java-sso-cas
【Happyjava】原创,转载请注明出处!