详解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
0
投稿
猜你喜欢
- 本文实例为大家分享了Android微信摇一摇功能的实现方法,供大家参考,具体内容如下import java.util.ArrayList;
- 简介本文介绍MyBatis-Plus的分页的方法。包括:不传参数时的默认结果查询不存在的数据手动包装page自定义SQL建库建表DROP D
- 现象: 1. 表面现象: 方法中输出的日志, 日志文件中找不到, 也没有任何报错(即@Async标注的方法没有执行, 也没有报错)2. 分析
- mybatis-plus作为mybatis的增强工具,简化了开发中的数据库操作。一旦遇到left join或right join的左右连接,
- Allatori混淆技术介绍Allatori是一个Java 混淆器,它属于第二代混淆器,因此它能够全方位地保护你的知识产权。 Allator
- 1.打开官网稍微学习一下,了解一下spring cloud是个什么东西,大概有哪些组件等https://spring.io/projects
- 上篇文章中我们介绍了浅谈Spring的两种配置容器,接下来我们就了解下spring中的FactoryBean的相关内容,具体如下。从Sess
- SpringBoot集成Mybatis时mybatis.mapper-locations和@MapperScan的作用1、mybatis.m
- 介绍该系统有三个角色,分别是:普通用户、房屋中介、管理员。普通用户的功能:浏览房屋信息、预约看房、和中介聊天、申请成为中介等等。房屋中介的功
- 本文实例为大家分享了C语言自定义扫雷游戏的具体代码,供大家参考,具体内容如下实现过程对于用C语言实现扫雷游戏得实现,可将游戏过程分为两个板块
- 正在尝试分配更低的访问权限?在进行Java编程时会给我们报出如下提示怎么办?这里我们将给大家介绍详细的解决方法。首先,查看,控制台给出的提示
- 简介optional类是java8中引入的针对NPE问题的一种优美处理方式,源码作者也希望以此替代null。历史1965年,英国一位名为To
- 在之前项目中有用到关于获取手机联系人的部分,闲置就想和大家分享一下,话不多说,上代码:java部分:package com.example.
- 你是否受够了每次修改静态文件都要重启服务器?有时候在一些公司前后端的职责没有那么的明确,往往后台人员也要去写一些页面,像jsp页面,或者其他
- /// <summary> /// 遍历Co
- pom.xml<dependency> <groupId>org.springframework.bo
- Java实现按行读取大文件String file = "F:" + File.separator + "a.t
- 使用maven的profile功能,我们可以实现多环境配置文件的动态切换,可参考我的上一篇博客。但随着SpringBoot项目越来越火,越来
- foreach 循环 list(map)直接上代码:整体需求就是1.分页对象里面有map map里面又有数组对象2.分页对象里面有list
- IDEA SpringBoot项目配置热更新的步骤1.在pom.xml中添加依赖:<dependency><groupId