详解spring cloud ouath2中的资源服务器
作者:小黄鸡1992 发布时间:2022-09-24 15:36:43
标签:spring,cloud,ouath,资源服务器
资源服务器就是业务服务 如用户服务,订单服务等 第三方需要到资源服务器调用接口获取资源
ResourceServerConfig
ResourceServerConfig是资源服务器的核心配置 用于验证token 与网关配置相似
其中.antMatchers("/**").access("#oauth2.hasScope('user')") 需要oauth_client_details表的scope配合 意思是访问所有资源 需要客户端有scope需要有user
@Configuration
@EnableResourceServer // 标识为资源服务器,请求服务中的资源,就要带着token过来,找不到token或token是无效访问不了资源
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级别权限控制
public class ResourceServerConfig extends ResourceServerConfigurerAdapter implements CommandLineRunner {
private final static Logger logger = LoggerFactory.getLogger(ResourceServerConfig.class);
public static final String RESOURCE_ID = "user";
/**
* 权限不足返回给前端json
*/
@Autowired
private CustomAccessDeniedHandlerConfig customAccessDeniedHandlerConfig;
@Autowired
private TokenStore tokenStore;
/**
* token无效返回前段json
*/
@Autowired
private AuthExceptionEntryPointConfig authExceptionEntryPointConfig;
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
// 当前资源服务器的资源id,认证服务会认证客户端有没有访问这个资源id的权限,有则可以访问当前服务
resources.tokenStore(tokenStore).resourceId(RESOURCE_ID)
// token无效异常的处理
.authenticationEntryPoint(authExceptionEntryPointConfig)
// 权限不足异常处理类
.accessDeniedHandler(customAccessDeniedHandlerConfig)
// 会话机制stateless开启
.stateless(true);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
// SpringSecurity不会使用也不会创建HttpSession实例 因为整个oauth2后使用token
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
// 开放swagger请求
.antMatchers("/swagger-ui.html", "/webjars/**", "/swagger-resources/**","/v2/**").permitAll()
// 所有请求,都需要有all范围(scope)
.antMatchers("/**").access("#oauth2.hasScope('user')").
anyRequest().authenticated().and().csrf()
.disable();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
AuthExceptionEntryPointConfig,CustomAccessDeniedHandlerConfig
用于异常返回前端json
@Component
public class CustomAccessDeniedHandlerConfig implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setStatus(HttpStatus.OK.value());
response.setHeader("Content-Type", "application/json;charset=UTF-8");
try {
Result result = new Result(403, "权限不足");
response.getWriter().write(new ObjectMapper().writeValueAsString(result));
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Component
public class AuthExceptionEntryPointConfig implements AuthenticationEntryPoint{
private final static Logger logger = LoggerFactory.getLogger(AuthExceptionEntryPointConfig.class);
@Value("${security.redirect-url}")
private String redirectUrl;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) {
Throwable cause = authException.getCause();
response.setStatus(HttpStatus.OK.value());
response.setHeader("Content-Type", "application/json;charset=UTF-8");
Result result;
try {
if (cause instanceof InvalidTokenException) {
result = new Result(402, "认证失败,无效或过期token");
response.getWriter().write(new ObjectMapper().writeValueAsString(result));
} else {
result = new Result(401, "认证失败,没有携带token");
response.sendRedirect(redirectUrl);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
TokenConfig
不多说
@Configuration
public class TokenConfig{
/**
* 使用redis存储
*/
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
public TokenStore tokenStore() {
return new RedisTokenStore(redisConnectionFactory);
}
}
application.yml
那么小伙伴又问了 既然网关验证token的有效性 那么资源服务器是不是就不用验证啦 答案是否 因为不添加配置 会报错 同样需要在application中添加以下配置
其他配置也spirng boot为准 这里不多说
security:
oauth2:
client:
client-id: user-vue
client-secret: 1234
resource:
token-info-uri: http://localhost:8001/oauth/check_token
来源:https://blog.csdn.net/qq_20143059/article/details/113766105


猜你喜欢
- 效果 使用compile 'site.gemus:openingstartanimation:1.0.0' //在gra
- 一、需要自定义登录结果的场景在我之前的文章中,做过登录验证流程的源码解析。其中比较重要的就是当我们登录成功的时候,是由Authenticat
- 前言本文主要给大家介绍了关于C#连接FTP时路径问题的相关内容,分享出来供大家参考学习,话不多说,来一起看看详细的介绍:今天在开发项目时,需
- 前言最近看了内部类后,总结一下,首先内部类嵌套在其他内部的类,根据出现的位置和关键字,可以分为以下四种类:成员内部类,静态内部类,方法内部类
- 本文实例讲述了C#实现功能强大的中国农历日历操作类。分享给大家供大家参考。具体如下:这个C#类定义了中国农历日历,除了可以输入正常的日历外还
- 本文实例讲述了C#编程实现查看剪切板内容的方法。分享给大家供大家参考,具体如下:using System;using System.Coll
- 一. 泛型概念的提出(为什么需要泛型)?首先,我们看下下面这段简短的代码:public class GenericTest {public
- 这篇文章主要介绍了spring boot 2整合swagger-ui过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的
- C#可以直接引用C++的DLL和转换JAVA写好的程序。最近由于工作原因接触这方面比较多,根据实际需求,我们通过一个具体例子把一个JAVA方
- 目录前言一、介绍一下GradientDrawable二、实现三、源码:总结前言今天和朋友聊到这个功能,刚开始的想法是自定义view,如何进行
- 本文实例为大家分享了Android端实现文件上传的具体代码,供大家参考,具体内容如下1)、新建一个Android项目命名为androidUp
- 前言制作无边框窗口时,系统自带阴影会消失,这时就需要我自己给窗口添加阴影以防止窗口融入背景。添加阴影的方法很简单,直接用effect就可以了
- 一、简介CyclicBarrier 字面意思回环栅栏(循环屏障),它可以实现让一组线程等待至某个状态(屏障点)之后再全部同时执行。叫做回环是
- 本文实例讲述了C#实现生成所有不重复的组合功能。分享给大家供大家参考,具体如下:给你几个字母,比如(a,b,c,d,e,f),要求生成所有不
- 在Servlet2.5中,我们要实现文件上传功能时,一般都需要借助第三方开源组件,例如Apache的commons-fileupload组件
- Java中的final关键字1、修饰类的成员变量 这是final的主要用途之一,和C/C++的const,即该成员被修饰为常量,意味着不可修
- Springboot启动不检查JPA的数据源配置1.问题有时我们使用spring boot ,在依赖中配置了spring data jpa的
- Java判断一个字符串是否有中文一般情况是利用Unicode编码(CJK统一汉字的编码区间:0x4e00–0x9fbb)的正则来做判断,但是
- 1. 网络爬虫是一个自动提取网页的程序,它为搜索引擎从万维网上下载网页,是搜索引擎的重要组成。传统爬虫从一个或若干初始网页的URL开始,获得
- 本文实例为大家分享了c语言实现可自定义的游戏地图的具体代码,供大家参考,具体内容如下博主相信每个人都有想做游戏的冲动,那么本文将给出一个用c