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

在整个系统中 ,认证服务器的作用是产生token和验证token的有效性,资源服务器是根据认证服务器的响应结果决定如何处理请求资源。
# 基本使用
# 1 引入依赖
使用 资源服务器功能首先需要按照 安全管理 的步骤开启 spring security 的相关功能。
然后再pom里增加以下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
<optional>true</optional>
</dependency>
接着在项目里配置
# 是否开启资源服务器功能,默认值为false
yishuifengxiao.security.resourceserver.enable=true
# 2 在项目中加入文件
@Configuration
@EnableWebSecurity
public class SecurityConfig extends AbstractSecurityConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
}
}
# 3 在配置中加入配置属性
主要加入的配置属性如下:
# 指向认证服务器的token校验地址
yishuifengxiao.security.resourceserver.token-check-url=http://192.168.0.172:8000/oauth/check_token
# 表示在出现异常时直接输出json响应
yishuifengxiao.security.handler.exception.returnType=json
# 4 资源管理
资源管理的用法请参见 易水公共组件 (opens new window)设置
# 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 使用 (opens new window)
# 其他配置
#是否开启资源服务器功能,默认为false
yishuifengxiao.security.resourceserver.enable=false
# 默认的重定向URL,默认为主页地址 /
yishuifengxiao.security.resourceserver.redirect-url=/
#出现异常时的处理方式,默认为json
yishuifengxiao.security.resourceserver.return-type=json
# 指向认证服务器里token校验地址,一般默认的uri为/oauth/check_token
yishuifengxiao.security.resourceserver.token-check-url=
# 自定义配置
# 自定义异常配置
在项目中配置一个名为resourceAuthenticationEntryPoint
的AuthenticationEntryPoint
实例即可。
@Bean("resourceAuthenticationEntryPoint")
public AuthenticationEntryPoint resourceAuthenticationEntryPoint(ResourceProperties resourceProperties,
ProcessHandler customHandle) {
ResourceAuthenticationEntryPoint resourceAuthenticationEntryPoint = new ResourceAuthenticationEntryPoint();
resourceAuthenticationEntryPoint.setResourceProperties(resourceProperties);
resourceAuthenticationEntryPoint.setCustomHandle(customHandle);
return resourceAuthenticationEntryPoint;
}
# 自定义token处理策略
在项目中配置一个名为customBearerTokenResolver
的BearerTokenResolver
实例即可
@Bean("customBearerTokenResolver")
public CustomBearerTokenResolver customBearerTokenResolver() {
return new CustomBearerTokenResolver();
}
资源链接
易水公共组件官方文档地址:http://doc.yishuifengxiao.com/
易水公共组件源码地址:https://gitee.com/zhiyubujian/common-starter
易水风萧个人博客 http://www.yishuifengxiao.com
相关博客