详解spring cloud ouath2中的资源服务器

 更新时间:2021年02月11日 08:17:01   作者:小黄鸡1992  
这篇文章主要介绍了spring cloud ouath2中的资源服务器的相关知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

资源服务器就是业务服务 如用户服务,订单服务等 第三方需要到资源服务器调用接口获取资源

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

到此这篇关于spring cloud ouath2中的资源服务器的文章就介绍到这了,更多相关spring cloud ouath2资源服务器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • MyBatis入门实例教程之创建一个简单的程序

    MyBatis入门实例教程之创建一个简单的程序

    这篇文章主要介绍了MyBatis入门创建一个简单的程序,在 MySQL 中创建数据库 mybatisdemo,编码为 utf8,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2022-02-02
  • 详解java中float与double的区别

    详解java中float与double的区别

    这篇文章主要介绍了JAVA中float与double的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04
  • java队列之queue用法实例分析

    java队列之queue用法实例分析

    这篇文章主要介绍了java队列之queue用法实例分析,Queue 队列就是一个先入先出(FIFO)的数据结构,Queue接口继承Collection接口。感兴趣的可以了解一下
    2020-07-07
  • SpringCloud-Gateway网关的使用实例教程

    SpringCloud-Gateway网关的使用实例教程

    Gateway网关在微服务架构中扮演了不可或缺的角色,通过集中化管理、智能路由和强大的过滤器机制,为构建高效、可扩展的微服务系统提供了有力支持,这篇文章主要介绍了SpringCloud-Gateway网关的使用,需要的朋友可以参考下
    2024-03-03
  • SpringMVC适配器模式作用范围介绍

    SpringMVC适配器模式作用范围介绍

    适配器这个词我们应该很熟悉,天天都在使用,手机充电时,电源线头头就叫电源适配器,干什么用的呢?把220V电压转换成手机充电时使用的电压,那么适配器是不是很好理解了,下面看一下
    2023-04-04
  • JavaBean和Map转换封装类的方法

    JavaBean和Map转换封装类的方法

    下面小编就为大家带来一篇JavaBean和Map转换封装类的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-10-10
  • 运用Spring Aop+注解实现日志记录

    运用Spring Aop+注解实现日志记录

    我们都知道Spring框架的两大特性分别是 IOC (控制反转)和 AOP (面向切面),这个是每一个Spring学习视频里面一开始都会提到的,这里,如果我们使用Aop来记录日志,那是再好不过了,感兴趣的朋友跟随小编一起学习下Spring Aop注解实现日志记录的过程吧
    2022-01-01
  • springboot 启动项目打印接口列表的实现

    springboot 启动项目打印接口列表的实现

    这篇文章主要介绍了springboot 启动项目打印接口列表的实现方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • 详解怎么用Java的super关键字

    详解怎么用Java的super关键字

    今天带大家学习Java中super关键字是怎么用的,文中有非常详细的介绍,对正在学习的小伙伴们很有帮助,需要的朋友可以参考下
    2021-06-06
  • SpringBoot项目启动过程动态修改接口请求路径的解决方案

    SpringBoot项目启动过程动态修改接口请求路径的解决方案

    在SpringBoot服务整合过程中,遇到了多个服务中相同RequestMapping路径导致的启动问题,解决方案是通过修改RequestMappingHandlerMapping类的getMappingForMethod方法,本文给大家介绍SpringBoot修改接口请求路径的解决方案,感兴趣的朋友一起看看吧
    2024-09-09

最新评论