在使用本组件之前,需要先搭建好认证服务器,其中认证服务器可以根据业务需要进行单机或集群部署。
整个系统的结果如图所示

在整个系统中 ,认证服务器的作用是产生token和验证token的有效性,资源服务器是根据认证服务器的响应结果决定如何处理请求资源。
1 引入依赖
完整的pom依赖文件如下
| <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.2.0.RELEASE</version>
 <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.yishuifengxiao.sso-client</groupId>
 <artifactId>demo</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>demo</name>
 <description>Demo project for Spring Boot</description>
 
 <properties>
 <java.version>1.8</java.version>
 </properties>
 
 <dependencies>
 
 <!--需要引入的组件-->
 <dependency>
 <groupId>com.yishuifengxiao.common</groupId>
 <artifactId>common-spring-boot-starter</artifactId>
 <version>4.1.2</version>
 </dependency>
 
 <dependency>
 <groupId>com.yishuifengxiao.common</groupId>
 <artifactId>oauth2-resource-starter</artifactId>
 <version>1.1.0</version>
 </dependency>
 <!--需要引入的组件-->
 
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-security</artifactId>
 </dependency>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 </dependencies>
 
 <build>
 <plugins>
 <plugin>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-maven-plugin</artifactId>
 </plugin>
 </plugins>
 </build>
 
 </project>
 
 | 
2 在项目中加入文件
| @Configuration@EnableWebSecurity
 public class SecurityConfig extends AbstractSecurityConfig {
 
 
 @Override
 protected void configure(HttpSecurity http) throws Exception {
 super.configure(http);
 }
 }
 
 | 
3 在配置中加入配置属性
主要加入的配置属性如下:
| # 只想认证服务器的token校验地址yishuifengxiao.security.resourceserver.userInfoUrl=http://192.168.0.172:8000/oauth/check_token
 # 表示在出现异常时直接输出json响应
 yishuifengxiao.security.handler.exception.returnType=json
 
 | 
4 资源管理
资源管理的用法请参见 易水公共组件设置
5 访问资源
在项目里加入以下代码
| @SpringBootApplication@RestController
 public class DemoApplication {
 
 @GetMapping("/me")
 public Authentication user(Authentication authentication) {
 
 return authentication;
 
 }
 
 public static void main(String[] args) {
 SpringApplication.run(DemoApplication.class, args);
 
 }
 
 }
 
 | 
完成上述配置以后,先从认证服务器中获取到access_token,然后再利用access_token访问资源服务器中的资源了。
例如当我们想要访问 /me时,即可通过 http://localhost:8080/me?access_token=认证服务器里获得token获取到资源信息了。
token的用法即可参见 access_token 使用