上一篇搭建了一个OAuth2认证服务器,可以生成token,这篇来改造下之前的订单微服务,使其能够认这个token令牌。

本篇针对订单服务要做三件事:

1,要让他知道自己是资源服务器,他知道这件事后,才会在前边加一个过滤器去验令牌(配置@EnableResourceServer 配置类)

2,要让他知道自己是什么资源服务器(配置资源服务器ID)

3,配置去哪里验令牌,怎么验令牌,要带什么信息去验 (配置@EnableWebSecurity 配置TokenServices,配置AuthenticationManager)

搭建资源服务器

++++++++++++++++++资源服务器现有的各个类++++++++++++++++++++++++++++

pom.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5.  
  6. <groupId>com.nb.security</groupId>
  7. <artifactId>nb-order-api</artifactId>
  8. <version>0.0.1-SNAPSHOT</version>
  9.  
  10. <properties>
  11. <java.version>1.8</java.version>
  12. </properties>
  13.  
  14. <dependencyManagement>
  15. <dependencies>
  16. <dependency>
  17. <!-- Import dependency management from Spring Boot -->
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-dependencies</artifactId>
  20. <version>2.1.6.RELEASE</version>
  21. <type>pom</type>
  22. <scope>import</scope>
  23. </dependency>
  24. <!--spring cloud-->
  25. <dependency>
  26. <groupId>org.springframework.cloud</groupId>
  27. <artifactId>spring-cloud-dependencies</artifactId>
  28. <version>Greenwich.SR2</version>
  29. <type>pom</type>
  30. <scope>import</scope>
  31. </dependency>
  32.  
  33. </dependencies>
  34.  
  35. </dependencyManagement>
  36.  
  37. <dependencies>
  38.  
  39. <dependency>
  40. <groupId>org.springframework.boot</groupId>
  41. <artifactId>spring-boot-starter-web</artifactId>
  42. </dependency>
  43.  
  44. <!--OAuth2-->
  45. <dependency>
  46. <groupId>org.springframework.cloud</groupId>
  47. <artifactId>spring-cloud-starter-oauth2</artifactId>
  48. </dependency>
  49.  
  50. <!--lombok-->
  51. <dependency>
  52. <groupId>org.projectlombok</groupId>
  53. <artifactId>lombok</artifactId>
  54. </dependency>
  55.  
  56. </dependencies>
  57.  
  58. <build>
  59. <plugins>
  60.  
  61. <!--指定JDK编译版本 -->
  62. <plugin>
  63. <groupId>org.apache.maven.plugins</groupId>
  64. <artifactId>maven-compiler-plugin</artifactId>
  65. <configuration>
  66. <source>1.8</source>
  67. <target>1.8</target>
  68. <encoding>UTF-8</encoding>
  69. </configuration>
  70. </plugin>
  71. <!-- 打包跳过测试 -->
  72. <plugin>
  73. <groupId>org.apache.maven.plugins</groupId>
  74. <artifactId>maven-surefire-plugin</artifactId>
  75. <configuration>
  76. <skipTests>true</skipTests>
  77. </configuration>
  78. </plugin>
  79.  
  80. <plugin>
  81. <groupId>org.springframework.boot</groupId>
  82. <artifactId>spring-boot-maven-plugin</artifactId>
  83. </plugin>
  84. </plugins>
  85. </build>
  86.  
  87. </project>

application.yml:

  1. server:
  2. port: 9060

OrderInfo.java :

  1. package com.nb.security.order;
  2.  
  3. import lombok.AllArgsConstructor;
  4. import lombok.Data;
  5. import lombok.NoArgsConstructor;
  6.  
  7. @Data
  8. @NoArgsConstructor
  9. @AllArgsConstructor
  10. public class OrderInfo {
  11.  
  12. private Long productId;
  13.  
  14. }

OrderController:

  1. package com.nb.security.order;
  2.  
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.web.bind.annotation.*;
  5. import org.springframework.web.client.RestTemplate;
  6.  
  7. @Slf4j
  8. @RestController
  9. @RequestMapping("/orders")
  10. public class OrderController {
  11.  
  12. private RestTemplate restTemplate = new RestTemplate();
  13.  
  14. @PostMapping
  15. public OrderInfo create(@RequestBody OrderInfo info){
  16. //查询价格
  17. // PriceInfo price = restTemplate.getForObject("http://localhost:9080/prices/"+info.getProductId(),PriceInfo.class);
  18. // log.info("price is "+price.getPrice());
  19. return info;
  20. }
  21.  
  22. @GetMapping
  23. public OrderInfo getInfo(@PathVariable Long id){
  24. log.info("getInfo: id is "+id);
  25. return new OrderInfo(id);
  26. }
  27.  
  28. }

启动类:

  1. package com.nb.security;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5.  
  6. @SpringBootApplication
  7. public class NbOrderApiApplication {
  8.  
  9. public static void main(String[] args) {
  10. SpringApplication.run(NbOrderApiApplication.class, args);
  11. }
  12.  
  13. }

PriceInfo.java (暂时先不用):

  1. package com.nb.security.order;
  2.  
  3. import lombok.Data;
  4.  
  5. import java.math.BigDecimal;
  6.  
  7. @Data
  8. public class PriceInfo {
  9.  
  10. private Long id;
  11.  
  12. private BigDecimal price;
  13. }

++++++++++++++++++资源服务器现有的各个类结束++++++++++++++++++++++++++++

1,在资源服务器pom哩加上 oauth2的依赖:

  1. <!--OAuth2-->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-oauth2</artifactId>
  5. </dependency>

2,新建资源服务器配置类,继承   ResourceServerConfigurerAdapter

  1. package com.nb.security.resource.server;
  2.  
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  5. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
  6. import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
  7. import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
  8.  
  9. /**
  10. * 资源服务器
  11. * 配置了@EnableResourceServer ,所有发往nb-order-api的请求,都会去请求头里找token,找不到不让你过
  12. */
  13. @Configuration
  14. @EnableResourceServer//告诉nb-order-api,你就是资源服务器
  15. public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
  16.  
  17. @Override
  18. public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
  19. //配置资源服务器的id,“现在我就是资源服务器order-server!!!”
  20. resources.resourceId("order-server");
  21. }
  22.  
  23. @Override
  24. public void configure(HttpSecurity http) throws Exception {
  25. /**
  26. * 进入nb-order-api的所有请求,哪些要拦截,哪些要放过,在这里配置
  27. */
  28. http.authorizeRequests()
  29. .antMatchers("/hello")
  30. .permitAll() //放过/haha不拦截
  31. .anyRequest().authenticated();//其余所有请求都拦截
  32. }
  33. }

ResourceServerConfigurerAdapter 有两个方法:

开篇说的1、2、3中的1和2已经完成了,下面做第3件事,怎么验令牌:

新建配置类:

  1. package com.nb.security.resource.server;
  2.  
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.security.authentication.AuthenticationManager;
  6. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  7. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  8. import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager;
  9. import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
  10. import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
  11.  
  12. /**
  13. * 怎么验发往本服务的请求头的令牌
  14. * 1,自定义tokenServices ,说明去哪里去验token
  15. * 2,重写authenticationManagerBean()方法,将AuthenticationManager暴露为一个Bean
  16. * 要认证跟用户相关的信息,一般用 AuthenticationManager
  17. *
  18. * 这样配置了后,所有发往nb-order-api的请求,
  19. * 需要验token的时候就会发请求去http://localhost:9090/oauth/check_token验token,获取到token对应的用户信息
  20. */
  21. @Configuration
  22. @EnableWebSecurity
  23. public class OAuth2WebSecurityConfig extends WebSecurityConfigurerAdapter{
  24.  
  25. /**
  26. * 通过这个Bean,去远程调用认证服务器,验token
  27. * @return
  28. */
  29. @Bean
  30. public ResourceServerTokenServices tokenServices(){
  31. RemoteTokenServices tokenServices = new RemoteTokenServices();
  32. tokenServices.setClientId("orderService");//在认证服务器配置的,订单服务的clientId
  33. tokenServices.setClientSecret("123456");//在认证服务器配置的,订单服务的ClientSecret
  34. tokenServices.setCheckTokenEndpointUrl("http://localhost:9090/oauth/check_token");
  35. return tokenServices;
  36. }
  37.  
  38. /**
  39. * 要认证跟用户相关的信息,一般用 AuthenticationManager
  40. * 覆盖这个方法,可以将AuthenticationManager暴露为一个Bean
  41. *
  42. * @return
  43. * @throws Exception
  44. */
  45. @Bean
  46. @Override
  47. public AuthenticationManager authenticationManagerBean() throws Exception {
  48. OAuth2AuthenticationManager authenticationManager = new OAuth2AuthenticationManager();
  49. authenticationManager.setTokenServices(tokenServices());//设置为自定义的TokenServices,去校验令牌
  50. return authenticationManager;
  51. }
  52. }

认证服务器关于订单服务的配置:

启动认证服务器,

启动订单 资源服务器,

访问认证服务器获取token  : localhost:9090/oauth/token

拿着 token 去资源服务器创建订单,注意,选择bearer类型的token,生成的请求头是这样的(注:Authorization的value值,postman生成的是以Bearer开头的,但是我看谷歌浏览器restclient插件生成的是bearer的B是小写):

在资源服务器里,可以通过该注解获取用户名:

错误的情况:

如果把资源服务器配置的resourceId改成了order-server222,请求创建订单,会受到如下的错误

如果资源服务器检验token的cilentID获取clientSecret写错了,后台会报错:

++++++++++++++++++++++分割线++++++++++++++++++++++

小结:

接上篇的认证服务器,本篇实现了资源服务器,以及与认证服务器的交互,怎么去验令牌。

遗留疑问:

认证服务器里面,配置资源服务器secret的时候,用passwordEncoder对123456进行了加密,而在资源服务器里,clientSecret确实明文的123456,这两者不需要一致么?

认证服务器里对资源服务器ClientId、 ClientSecret配置:

资源服务器验令牌携带的ClientId、 ClientSecret:

代码github :https://github.com/lhy1234/springcloud-security/tree/chapt-4-5-resource-server

Spring Cloud微服务安全实战_4-5_搭建OAuth2资源服务器的更多相关文章

  1. Spring cloud微服务安全实战-7-3prometheus环境搭建

    Prmetheus 主要用来做来Metrics的监控和报警,这张图是官方的架构图. 这是他的核心 它的作用是根据我们的配置去完成数据的采集.服务的发现,以及数据的存储. 这是服务的发现,通过Servi ...

  2. Spring cloud微服务安全实战_汇总

    Spring cloud微服务安全实战 https://coding.imooc.com/class/chapter/379.html#Anchor Spring Cloud微服务安全实战-1-1 课 ...

  3. 《Spring Cloud微服务 入门 实战与进阶》

    很少在周末发文,还是由于昨晚刚收到实体书,还是耐不住性子马上发文了. 一年前,耗时半年多的时间,写出了我的第一本书<Spring Cloud微服务-全栈技术与案例解析>. 时至今日,一年的 ...

  4. Spring Cloud微服务安全实战_00_前言

    一.前言: 一直以来对服务安全都很感兴趣,所以就学习.这是学习immoc的 jojo老师的 <Spring Cloud微服务安全实战课程>的笔记,讲的很好. 课程简介:  二.最终形成的架 ...

  5. Spring cloud微服务安全实战 最新完整教程

    课程资料获取链接:点击这里 采用流行的微服务架构开发,应用程序访问安全将会面临更多更复杂的挑战,尤其是开发者最关心的三大问题:认证授权.可用性.可视化.本课程从简单的API安全入手,过渡到复杂的微服务 ...

  6. Spring Cloud微服务安全实战_4-3_订单微服务&价格微服务

    实现一个场景: 订单微服务: POM: <?xml version="1.0" encoding="UTF-8"?> <project xml ...

  7. Spring Cloud微服务安全实战_4-4_OAuth2协议与微服务安全

    接上篇文章,在这个流程中,PostMan可以代表客户端应用,订单服务是资源服务器,唯一缺少的是 认证服务器 ,下面来搭建认证服务器 项目结构: Pom.xml : DependencyManager ...

  8. Spring cloud微服务安全实战-6-8sentinel限流实战

    阿里2018年开源的. 简单来说就是干三件事,最终的结果就是保证你的服务可用,不会崩掉.保证服务高可用. 流控 先从最简单的场景来入手. 1.引用一个依赖, 2,声明一个资源. 3.声明一个规则 注意 ...

  9. Spring cloud微服务安全实战-6-4权限控制改造

    授权,权限的控制 令牌里的scope包含fly就有权限访问.根据Oauth的scope来做权限控制, 要让@PreAuthorize生效,就要在启动类里面写一个注解. 里面有一个属性叫做,就是在方法的 ...

随机推荐

  1. Unity开发实战探讨-资源的加载释放最佳策略简要心得

    Unity开发实战探讨-资源的加载释放最佳策略简要心得 看过我另外一篇关于Unity资源释放随笔<Unity开发实战探讨-资源的加载释放最佳策略>如果觉得略微复杂,那么下面是一些比较简要的 ...

  2. raspberry pi 4b 常见的一些配置信息

    实验记录地址 https://gitee.com/dhclly/icepi.raspberry-pi 针脚图 面包板 gnd & vcc VCC:电路的供电电压: GND:指板子里面总的地线. ...

  3. C#猜测识别文件编码

    项目 gitee地址:https://gitee.com/dhclly/IceDog.SmallProject/tree/master/src/IceDog.SmallProject.CodeConv ...

  4. 如何在 Knative 中部署 WebSocket 和 gRPC 服务?

    作者 | 冬岛  阿里云容器平台工程师 导读:虽然说 Knative 默认就支持 WebSocket 和 gRPC,但在使用中会发现,有时想要把自己的 WebSocket 或 gRPC 部署到 Kna ...

  5. java架构之路-(nginx使用详解)nginx的安装和基本配置

    Linux是一套免费使用和自由传播的类Unix操作系统,是一个基于POSIX和Unix的多用户.多任务.支持多线程和多CPU的操作系统.它能运行主要的Unix工具软件.应用程序和网络协议.它支持32位 ...

  6. Linux安装centos,网络net8模式ping不通www.baidu.com或者ping不通主机

    1.Linux安装centos,网络net8模式ping不通www.baidu.com或者ping不通主机. 我使用的是net8模式.配置如下所示,保证可以ping通www.baidu.com或者pi ...

  7. 练手WPF(四)——贪吃蛇小游戏的简易实现(上)

    一. 游戏界面首先,按照惯例,编辑MainWindow.xaml,先将游戏界面制作好.非常简单:(1)主游戏区依然使用我们熟悉的Canvas控件,大小为640X480像素,设定每小格子为20px,所以 ...

  8. TinyMCE编辑器图片上传扩展(base64方式),asp.net mvc5

    编辑器上传图片一般都是先上传到服务器中,若是用户取消或忘记提交表单就产生一张废图在空间里面,时间一长就产生大量占用空间的无用图片,现在就试试提交前先用base64,提交后,在后台处理编辑器内容中的&l ...

  9. 微信分享网页时自定义缩略图和简介(.net版本)

    要实现微信分享网页时自定义缩略图和简介,需开发者在公众平台网站中创建公众号.获取接口权限后,通过微信JS-SDK的分享接口,来实现微信分享功能. 下面来说明实现步骤. 第一部分 准备步骤 步骤一:注册 ...

  10. RookeyFrame模块初始化

    上一篇讲了下线上创建模块,这一次讲下线下创建的模块如何初始化,实体类的创建可参考Demo中的客户主数据模块 首先讲下model类创建中的约定: 1.所有数据模型继承BaseEntity 2.需要绑定枚 ...