Spring Security 解析(六) —— 基于JWT的单点登陆(SSO)开发及原理解析
在学习Spring Cloud 时,遇到了授权服务oauth 相关内容时,总是一知半解,因此决定先把Spring Security 、Spring Security Oauth2 等权限、认证相关的内容、原理及设计学习并整理一遍。本系列文章就是在学习的过程中加强印象和理解所撰写的,如有侵权请告知。
项目环境:
JDK1.8
Spring boot 2.x
Spring Security 5.x
单点登录(Single Sign On),简称为SSO,是目前比较流行的企业业务整合的解决方案之一。 SSO的定义是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统。 单点登陆本质上也是OAuth2的使用,所以其开发依赖于授权认证服务,如果不清楚的可以看我的上一篇文章。
一、 单点登陆 Demo开发
从单点登陆的定义上来看就知道我们需要新建个应用程序,我把它命名为 security-sso-client。接下的开发就在这个应用程序上了。
一、Maven 依赖
主要依赖 spring-boot-starter-security、spring-security-oauth2-autoconfigure、spring-security-oauth2 这3个。其中 spring-security-oauth2-autoconfigure 是Spring Boot 2.X 才有的。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><<img src="https://github.com/BUG9/spring-security/network/alert/pom.xml/org.springframework.security.oauth:spring-security-oauth2/open--><version>2.3.5.RELEASE</version></dependency>" style="margin: auto" />
二、单点配置 @EnableOAuth2Sso
单点的基础配置引入是依赖 @EnableOAuth2Sso 实现的,在Spring Boot 2.x 及以上版本 的 @EnableOAuth2Sso 是在 spring-security-oauth2-autoconfigure 依赖里的。我这里简单配置了一下:
@Configuration
@EnableOAuth2Sso
public class ClientSecurityConfig extends WebSecurityConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/","/error","/login").permitAll().anyRequest().authenticated().and().csrf().disable();}
}
因为单点期间可能存在某些问题,会重定向到 /error ,所以我们把 /error 设置成无权限访问。
三、测试接口及页面
测试接口
@RestController
@Slf4j
public class TestController {@GetMapping("/client/{clientId}")public String getClient(@PathVariable String clientId) {return clientId;}
}
测试页面
<<img src="http://localhost:8091/client/1">跳转到OSS-client-1</a><a href="http://localhost:8092/client/2">跳转到OSS-client-2</a></body></html>" style="margin: auto" />
四、单点配置文件配置授权信息
由于我们要测试多应用间的单点,所以我们至少需要2个单点客户端,我这边通过Spring Boot 的多环境配置实现。