react hooks

朋友不允许朋友写用户身份验证。 厌倦了管理自己的用户? 立即尝试Okta的API和Java SDK。 数分钟之内即可在任何应用程序中对用户进行身份验证,管理和保护。

所以你想完全React,是吗? 大! React式编程是使您的应用程序更高效的一种越来越流行的方式。 响应式应用程序异步调用响应,而不是调用资源并等待响应。 这使他们可以释放处理能力,仅在必要时执行处理,并且比其他系统更有效地扩展。

Java生态系统在React框架中占有相当大的份额,其中包括Play框架,Ratpack,Vert.x和Spring WebFlux。 像React式编程一样,微服务架构可以帮助大型团队快速扩展,并且可以使用上述任何出色的框架进行构建。

今天,我想向您展示如何使用Spring Cloud Gateway,Spring Boot和Spring WebFlux构建React性微服务架构。 我们将利用Spring Cloud Gateway,因为API网关通常是云原生微服务体系结构中的重要组件,为所有后端微服务提供了聚合层。

本教程向您展示如何使用REST API构建微服务,该API返回新车列表。 您将使用Eureka进行服务发现,并使用Spring Cloud Gateway将请求路由到微服务。 然后,您将集成Spring Security,以便只有经过身份验证的用户才能访问您的API网关和微服务。


先决条件: HTTPie (或cURL), Java 11+和Internet连接。

Spring Cloud Gateway与Zuul

Zuul是Netflix的API网关。 Zuul于2013年首次发布,最初并不具有React性,但Zuul 2是彻底的重写,使其具有React性。 不幸的是,Spring Cloud不支持Zuul 2 ,并且可能永远不支持。

现在,Spring Cloud Gateway是Spring Cloud Team首选的API网关实现。 它基于Spring 5,Reactor和Spring WebFlux构建。 不仅如此,它还包括断路器集成,使用Eureka进行服务发现以及与OAuth 2.0集成容易得多

让我们深入。

创建一个Spring Cloud Eureka Server项目

首先创建一个目录来保存所有项目,例如spring-cloud-gateway 。 在终端窗口中导航至它,并创建一个包含Spring Cloud Eureka Server作为依赖项的discovery-service项目。

http https://start.spring.io/starter.zip javaVersion==11 artifactId==discovery-service \name==eureka-service baseDir==discovery-service \dependencies==cloud-eureka-server | tar -xzvf -

上面的命令使用HTTPie 。 我强烈建议安装它。 您也可以使用curl 。 运行curl https://start.spring.io以查看语法。

在其主类上添加@EnableEurekaServer以将其启用为Eureka服务器。

import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;@EnableEurekaServer
@SpringBootApplication
public class EurekaServiceApplication {...}

将以下属性添加到项目的src/main/resources/application.properties文件中,以配置其端口并关闭Eureka注册。

server.port=8761
eureka.client.register-with-eureka=false

要使discovery-service在Java 11+上运行,请添加对JAXB的依赖关系。

<dependency><groupId>org.glassfish.jaxb</groupId><artifactId>jaxb-runtime</artifactId>
</dependency>

使用./mvnw spring-boot:run或通过在IDE中运行它来启动项目。

创建一个Spring Cloud Gateway项目

接下来,创建一个包含一些Spring Cloud依赖项的api-gateway项目。

http https://start.spring.io/starter.zip javaVersion==11 artifactId==api-gateway \name==api-gateway baseDir==api-gateway \dependencies==actuator,cloud-eureka,cloud-feign,cloud-gateway,cloud-hystrix,webflux,lombok | tar -xzvf -

一分钟后,我们将重新配置该项目。

使用Spring WebFlux创建React式微服务

汽车微服务将包含此示例代码的很大一部分,因为它包含支持CRUD(创建,读取,更新和删除)的功能齐全的REST API。

使用start.spring.io创建car-service项目:

http https://start.spring.io/starter.zip javaVersion==11 artifactId==car-service \name==car-service baseDir==car-service \dependencies==actuator,cloud-eureka,webflux,data-mongodb-reactive,flapdoodle-mongo,lombok | tar -xzvf -

此命令中的dependencies参数很有趣。 您可以看到其中包括Spring WebFlux,以及MongoDB。 Spring Data还为Redis和Cassandra提供了响应式驱动程序。

您可能还对R2DBC (React性关系数据库连接)感兴趣,这是将React性编程API引入SQL数据库的一种尝试。 在本示例中,我没有使用它,因为在start.spring.io上尚不可用。

使用Spring WebFlux构建REST API

我是大众的忠实拥护者,尤其是经典的公交车和bug车。 您是否知道大众在未来几年内将推出大量电动汽车? 我对ID Buzz感到非常兴奋! 它具有经典曲线,全电动。 它甚至拥有350+的马力!

如果您不熟悉ID Buzz,这是大众汽车的照片。


让我们从这个API示例中获得一些乐趣,并将电动VW用于我们的数据集。 该API将跟踪各种汽车名称和发布日期。

src/main/java/…​/CarServiceApplication.java添加Eureka注册,示例数据初始化和响应式REST API:

package com.example.carservice;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;import java.time.LocalDate;
import java.time.Month;
import java.util.Set;
import java.util.UUID;@EnableEurekaClient (1)
@SpringBootApplication
@Slf4j (2)
public class CarServiceApplication {public static void main(String[] args) {SpringApplication.run(CarServiceApplication.class, args);}@Bean (3)ApplicationRunner init(CarRepository repository) {// Electric VWs from https://www.vw.com/electric-concepts/// Release dates from https://www.motor1.com/features/346407/volkswagen-id-price-on-sale/Car ID = new Car(UUID.randomUUID(), "ID.", LocalDate.of(2019, Month.DECEMBER, 1));Car ID_CROZZ = new Car(UUID.randomUUID(), "ID. CROZZ", LocalDate.of(2021, Month.MAY, 1));Car ID_VIZZION = new Car(UUID.randomUUID(), "ID. VIZZION", LocalDate.of(2021, Month.DECEMBER, 1));Car ID_BUZZ = new Car(UUID.randomUUID(), "ID. BUZZ", LocalDate.of(2021, Month.DECEMBER, 1));Set<Car> vwConcepts = Set.of(ID, ID_BUZZ, ID_CROZZ, ID_VIZZION);return args -> {repository.deleteAll() (4).thenMany(Flux.just(vwConcepts).flatMap(repository::saveAll)).thenMany(repository.findAll()).subscribe(car -> log.info("saving " + car.toString())); (5)};}
}@Document
@Data
@NoArgsConstructor
@AllArgsConstructor
class Car { (6)@Idprivate UUID id;private String name;private LocalDate releaseDate;
}interface CarRepository extends ReactiveMongoRepository<Car, UUID> {
} (7)@RestController
class CarController { (8)private CarRepository carRepository;public CarController(CarRepository carRepository) {this.carRepository = carRepository;}@PostMapping("/cars")@ResponseStatus(HttpStatus.CREATED)public Mono<Car> addCar(@RequestBody Car car) { (9)return carRepository.save(car);}@GetMapping("/cars")public Flux<Car> getCars() { (10)return carRepository.findAll();}@DeleteMapping("/cars/{id}")public Mono<ResponseEntity<Void>> deleteCar(@PathVariable("id") UUID id) {return carRepository.findById(id).flatMap(car -> carRepository.delete(car).then(Mono.just(new ResponseEntity<Void>(HttpStatus.OK)))).defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND));}
}
  1. 添加@EnableEurekaClient注释以进行服务发现
  2. @Slf4j是Lombok的便捷注释,可用于登录类
  3. ApplicationRunner bean用默认数据填充MongoDB
  4. 删除MongoDB中的所有现有数据,以免添加新数据
  5. 订阅结果,以便调用deleteAll()saveAll()
  6. 带有Spring Data NoSQL和Lombok注释的Car类,以减少样板
  7. CarRepository接口扩展了ReactiveMongoRepository ,几乎没有任何代码,可为您提供CRUDability!
  8. 使用CarRepository执行CRUD操作的CarController
  9. Spring WebFlux返回单个对象的Mono发布者
  10. 返回多个对象的Flex发布者

如果使用IDE来构建项目,则需要为IDE设置Lombok 。

您还需要修改car-service项目的application.properties以设置其名称和端口。

spring.application.name=car-service
server.port=8081

运行MongoDB

运行MongoDB的最简单方法是从car-service/pom.xml的flappoodle依赖项中删除test范围。 这将导致您的应用程序启动嵌入式MongoDB依赖关系。

<dependency><groupId>de.flapdoodle.embed</groupId><artifactId>de.flapdoodle.embed.mongo</artifactId><!--<scope>test</scope>-->
</dependency>

您还可以使用Homebrew安装和运行MongoDB。

brew tap mongodb/brew
brew install mongodb-community@4.2
mongod

或者,使用Docker:

docker run -d -it -p 27017:27017 mongo

使用WebFlux传输数据

这样就完成了使用Spring WebFlux构建REST API所需完成的所有工作。

“可是等等!” 你可能会说。 “我以为WebFlux就是关于流数据的?”

在此特定示例中,您仍然可以从/cars端点流式传输数据,但不能在浏览器中。

除了使用服务器发送事件或WebSocket之外,浏览器无法使用流。 但是,非浏览器客户端可以通过发送具有application/stream+json值的Accept报头来获取JSON流(感谢Rajeev Singh的技巧)。

可以通过启动浏览器并使用HTTPie发出请求测试此时一切正常。 但是,编写自动化测试要好得多!

使用WebTestClient测试您的WebFlux API

WebClient是Spring WebFlux的一部分,可用于发出响应请求,接收响应以及使用有效负载填充对象。 伴随类WebTestClient可用于测试WebFlux API。 它包含与WebClient相似的请求方法,以及检查响应正文,状态和标头的方法。

修改car-service项目中的src/test/java/…​/CarServiceApplicationTests.java类以包含以下代码。

package com.example.carservice;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Mono;import java.time.LocalDate;
import java.time.Month;
import java.util.Collections;
import java.util.UUID;@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,properties = {"spring.cloud.discovery.enabled = false"})
public class CarServiceApplicationTests {@AutowiredCarRepository carRepository;@AutowiredWebTestClient webTestClient;@Testpublic void testAddCar() {Car buggy = new Car(UUID.randomUUID(), "ID. BUGGY", LocalDate.of(2022, Month.DECEMBER, 1));webTestClient.post().uri("/cars").contentType(MediaType.APPLICATION_JSON_UTF8).accept(MediaType.APPLICATION_JSON_UTF8).body(Mono.just(buggy), Car.class).exchange().expectStatus().isCreated().expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8).expectBody().jsonPath("$.id").isNotEmpty().jsonPath("$.name").isEqualTo("ID. BUGGY");}@Testpublic void testGetAllCars() {webTestClient.get().uri("/cars").accept(MediaType.APPLICATION_JSON_UTF8).exchange().expectStatus().isOk().expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8).expectBodyList(Car.class);}@Testpublic void testDeleteCar() {Car buzzCargo = carRepository.save(new Car(UUID.randomUUID(), "ID. BUZZ CARGO",LocalDate.of(2022, Month.DECEMBER, 2))).block();webTestClient.delete().uri("/cars/{id}", Collections.singletonMap("id", buzzCargo.getId())).exchange().expectStatus().isOk();}
}

为了证明它有效,请运行./mvnw test 。 测试通过后,请拍一下自己的背!


如果您使用的是Windows,请使用mvnw test

将Spring Cloud Gateway与React式微服务一起使用

要在同一IDE窗口中编辑所有三个项目,我发现创建一个聚合器pom.xml很有用。 在项目的父目录中创建pom.xml文件,并将下面的XML复制到其中。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.okta.developer</groupId><artifactId>reactive-parent</artifactId><version>1.0.0-SNAPSHOT</version><packaging>pom</packaging><name>reactive-parent</name><modules><module>discovery-service</module><module>car-service</module><module>api-gateway</module></modules>
</project>

创建此文件后,您应该能够在IDE中将其作为项目打开,并可以轻松地在项目之间导航。

api-gateway项目中,将@EnableEurekaClient添加到主类以使其能够感知Eureka。

import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@EnableEurekaClient
@SpringBootApplication
public class ApiGatewayApplication {...}

然后,修改src/main/resources/application.properties文件以配置应用程序名称。

spring.application.name=gateway

ApiGatewayApplication创建一个RouteLocator bean,以配置路由。 您可以使用YAML配置Spring Cloud Gateway,但我更喜欢Java。

package com.example.apigateway;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;@EnableEurekaClient
@SpringBootApplication
public class ApiGatewayApplication {public static void main(String[] args) {SpringApplication.run(ApiGatewayApplication.class, args);}@Beanpublic RouteLocator customRouteLocator(RouteLocatorBuilder builder) {return builder.routes().route("car-service", r -> r.path("/cars").uri("lb://car-service")).build();}
}

更改完这些代码后,您应该能够启动所有三个Spring Boot应用程序并点击http://localhost:8080/cars

$ http :8080/cars
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
transfer-encoding: chunked[{"id": "ff48f617-6cba-477c-8e8f-2fc95be96416","name": "ID. CROZZ","releaseDate": "2021-05-01"},{"id": "dd6c3c32-724c-4511-a02c-3348b226160a","name": "ID. BUZZ","releaseDate": "2021-12-01"},{"id": "97cfc577-d66e-4a3c-bc40-e78c3aab7261","name": "ID.","releaseDate": "2019-12-01"},{"id": "477632c8-2206-4f72-b1a8-e982e6128ab4","name": "ID. VIZZION","releaseDate": "2021-12-01"}
]

添加REST API以检索您喜欢的汽车

创建一个/fave-cars终结点,以/fave-cars不是您最喜欢的汽车。

首先,添加一个负载平衡的WebClient.Builder bean。

@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder() {return WebClient.builder();
}

然后在同一文件中的ApiGatewayApplication类下添加Car POJO和FaveCarsController

public class ApiGatewayApplication {...}
class Car {...}
class FaveCarsController {...}

使用WebClient检索汽车并过滤掉您不喜欢的汽车。

@Data
class Car {private String name;private LocalDate releaseDate;
}@RestController
class FaveCarsController {private final WebClient.Builder carClient;public FaveCarsController(WebClient.Builder carClient) {this.carClient = carClient;}@GetMapping("/fave-cars")public Flux<Car> faveCars() {return carClient.build().get().uri("lb://car-service/cars").retrieve().bodyToFlux(Car.class).filter(this::isFavorite);}private boolean isFavorite(Car car) {return car.getName().equals("ID. BUZZ");}
}

如果您没有使用自动为您导入的IDE,则需要将以下内容复制/粘贴到ApiGatewayApplication.java的顶部:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

重新启动网关应用程序以查看http://localhost:8080/fave-cars终结点仅返回ID Buzz。


Hystrix的故障转移呢?

在撰写本文时,Spring Cloud Gateway仅支持Hystrix 。 Spring Cloud不赞成对Hystrix的直接支持,而推荐使用Spring Cloud Breaker 。 不幸的是,该库尚未发布GA版本,因此我决定不使用它。

要将Hystrix与Spring Cloud Gateway结合使用,可以向car-service路线添加过滤器,如下所示:

.route("car-service", r -> r.path("/cars").filters(f -> f.hystrix(c -> c.setName("carsFallback").setFallbackUri("forward:/cars-fallback"))).uri("lb://car-service/cars"))
.build();

然后创建一个CarsFallback控制器来处理/cars-fallback路由。

@RestController
class CarsFallback {@GetMapping("/cars-fallback")public Flux<Car> noCars() {return Flux.empty();}
}

首先,重新启动网关,并确认http://localhost:8080/cars可以正常工作。 然后关闭汽车服务,再试一次,您会看到它现在返回一个空数组。 重新启动汽车服务,您将再次看到该列表。

您已经使用Spring Cloud Gateway和Spring WebFlux构建了弹性和React性的微服务架构。 现在让我们看看如何保护它!

Feign与Spring Cloud Gateway怎么样?

如果您想在WebFlux应用程序中使用Feign,请参阅feignReact项目。 在此特定示例中,我不需要Feign。

带有OAuth 2.0的安全Spring Cloud Gateway

OAuth 2.0是用于委托访问API的授权框架。 OIDC(或OpenID Connect)是OAuth 2.0之上的薄层,可提供身份验证。 Spring Security对这两个框架都提供了出色的支持,Okta也是如此。

您可以通过构建自己的服务器或使用开源实现来在没有云身份提供商的情况下使用OAuth 2.0和OIDC。 但是,你会不会宁愿只是使用的东西,总是在像1563?

如果您已经有Okta帐户,请参见下面的在Okta中创建Web应用程序。 否则,我们创建了一个Maven插件,该插件配置了一个免费的Okta开发者帐户+一个OIDC应用程序(不到一分钟!)。

要使用它,请运行: ./mvnw com.okta:okta-maven-plugin:setup./mvnw com.okta:okta-maven-plugin:setup创建一个帐户并配置您的Spring Boot应用程序以与Okta一起使用。

在Okta中创建Web应用程序

登录到您的1563开发者帐户(或者注册,如果你没有一个帐户)。

  1. 在“应用程序”页面上,选择添加应用程序
  2. 在“创建新应用程序”页面上,选择“ Web”
  3. 为您的应用提供一个令人难忘的名称,将http://localhost:8080/login/oauth2/code/okta为登录重定向URI,选择刷新令牌(除了授权代码),然后点击完成

将发行者(位于API >授权服务器下),客户端ID和客户端密钥复制到两个项目的application.properties中。

okta.oauth2.issuer=$issuer
okta.oauth2.client-id=$clientId
okta.oauth2.client-secret=$clientSecret

接下来,将Okta Spring Boot启动器和Spring Cloud Security添加到网关的pom.xml

<dependency><groupId>com.okta.spring</groupId><artifactId>okta-spring-boot-starter</artifactId><version>1.2.1</version>
</dependency>
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-security</artifactId>
</dependency>

这就是添加Okta OIDC登录所需要做的一切! 重新启动您的Gateway应用程序,并在浏览器中导航到http://localhost:8080/fave-cars ,以将其重定向到Okta以进行用户授权。


使您的网关成为OAuth 2.0资源服务器

您可能不会在网关本身上为您的应用程序构建UI。 您可能会改用SPA或移动应用程序。 要将网关配置为充当资源服务器(查找带有承载令牌的Authorization标头),请在与主类相同的目录中添加新的SecurityConfiguration类。

package com.example.apigateway;import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfiguration {@Beanpublic SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {// @formatter:offhttp.authorizeExchange().anyExchange().authenticated().and().oauth2Login().and().oauth2ResourceServer().jwt();return http.build();// @formatter:on}
}

带有Spring Cloud Gateway的CORS

如果您将SPA用于UI,则还需要配置CORS。 您可以通过向CorsWebFilter添加CorsWebFilter bean来实现。

@Bean
CorsWebFilter corsWebFilter() {CorsConfiguration corsConfig = new CorsConfiguration();corsConfig.setAllowedOrigins(List.of("*"));corsConfig.setMaxAge(3600L);corsConfig.addAllowedMethod("*");corsConfig.addAllowedHeader("*");UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", corsConfig);return new CorsWebFilter(source);
}

确保您的进口商品与以下商品相符。

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

Spring Cloud Gateway的文档介绍了如何使用YAML或WebFluxConfigurer配置CORS。 不幸的是,我无法任其工作。

使用WebTestClient和JWT测试网关

如果您在网关中配置了CORS,则可以测试它是否可以与WebTestClient一起使用。 用以下代码替换ApiGatewayApplicationTests的代码。

import java.util.Map;
import java.util.function.Consumer;import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,properties = {"spring.cloud.discovery.enabled = false"})
public class ApiGatewayApplicationTests {@AutowiredWebTestClient webTestClient;@MockBean (1)ReactiveJwtDecoder jwtDecoder;@Testpublic void testCorsConfiguration() {Jwt jwt = jwt(); (2)when(this.jwtDecoder.decode(anyString())).thenReturn(Mono.just(jwt)); (3)WebTestClient.ResponseSpec response = webTestClient.put().uri("/").headers(addJwt(jwt)) (4).header("Origin", "http://example.com").exchange();response.expectHeader().valueEquals("Access-Control-Allow-Origin", "*");}private Jwt jwt() {return new Jwt("token", null, null,Map.of("alg", "none"), Map.of("sub", "betsy"));}private Consumer<HttpHeaders> addJwt(Jwt jwt) {return headers -> headers.setBearerAuth(jwt.getTokenValue());}
}
  1. 模拟ReactiveJwtDecoder以便您设置期望值并在解码时返回模拟
  2. 创建一个新的JWT
  3. 解码后返回相同的JWT
  4. 将JWT添加到带有Bearer前缀的Authorization标头中

我喜欢WebTestClient如何让您如此轻松地设置安全标头!

您已将Spring Cloud Gateway配置为使用OIDC登录并用作OAuth 2.0资源服务器,但是car服务仍可在端口8081 。 我们修复一下,以便只有网关可以与它进行对话。

微服务通信的安全网关

将Okta Spring Boot启动器添加到car-service/pom.xml

<dependency><groupId>com.okta.spring</groupId><artifactId>okta-spring-boot-starter</artifactId><version>1.2.1</version>
</dependency>

okta.*属性从网关的application.properties复制到汽车服务的属性。 然后创建一个SecurityConfiguration类,使该应用程序成为OAuth 2.0资源服务器。

package com.example.carservice;import com.okta.spring.boot.oauth.Okta;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfiguration {@Beanpublic SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {// @formatter:offhttp.authorizeExchange().anyExchange().authenticated().and().oauth2ResourceServer().jwt();Okta.configureResourceServer401ResponseBody(http);return http.build();// @formatter:on}
}

而已! 重新启动您的汽车服务应用程序,现在它已受到匿名入侵者的保护。

$ http :8081/cars
HTTP/1.1 401 Unauthorized
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: text/plain
...401 Unauthorized

使用WebTestClient和JWT测试您的微服务

启用安全性后,您在car-service项目中添加的测试将不再起作用。 修改CarServiceApplicationTests.java的代码,以将JWT访问令牌添加到每个请求。

package com.example.carservice;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Mono;import java.time.LocalDate;
import java.time.Month;
import java.util.Map;
import java.util.UUID;
import java.util.function.Consumer;import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,properties = {"spring.cloud.discovery.enabled = false"})
public class CarServiceApplicationTests {@AutowiredCarRepository carRepository;@AutowiredWebTestClient webTestClient;@MockBeanReactiveJwtDecoder jwtDecoder;@Testpublic void testAddCar() {Car buggy = new Car(UUID.randomUUID(), "ID. BUGGY", LocalDate.of(2022, Month.DECEMBER, 1));Jwt jwt = jwt();when(this.jwtDecoder.decode(anyString())).thenReturn(Mono.just(jwt));webTestClient.post().uri("/cars").contentType(MediaType.APPLICATION_JSON_UTF8).accept(MediaType.APPLICATION_JSON_UTF8).headers(addJwt(jwt)).body(Mono.just(buggy), Car.class).exchange().expectStatus().isCreated().expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8).expectBody().jsonPath("$.id").isNotEmpty().jsonPath("$.name").isEqualTo("ID. BUGGY");}@Testpublic void testGetAllCars() {Jwt jwt = jwt();when(this.jwtDecoder.decode(anyString())).thenReturn(Mono.just(jwt));webTestClient.get().uri("/cars").accept(MediaType.APPLICATION_JSON_UTF8).headers(addJwt(jwt)).exchange().expectStatus().isOk().expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8).expectBodyList(Car.class);}@Testpublic void testDeleteCar() {Car buzzCargo = carRepository.save(new Car(UUID.randomUUID(), "ID. BUZZ CARGO",LocalDate.of(2022, Month.DECEMBER, 2))).block();Jwt jwt = jwt();when(this.jwtDecoder.decode(anyString())).thenReturn(Mono.just(jwt));webTestClient.delete().uri("/cars/{id}", Map.of("id", buzzCargo.getId())).headers(addJwt(jwt)).exchange().expectStatus().isOk();}private Jwt jwt() {return new Jwt("token", null, null,Map.of("alg", "none"), Map.of("sub", "dave"));}private Consumer<HttpHeaders> addJwt(Jwt jwt) {return headers -> headers.setBearerAuth(jwt.getTokenValue());}
}

再次运行测试,一切都将通过!

Spring Security 5.2中的模拟JWT支持

感谢Josh Cummings在JWT和WebTestClient方面的帮助。 Josh预览了Spring Security 5.2中的模拟JWT支持。

this.webTestClient.mutateWith(jwt()).post(...)

Josh还提供了一个示例测试,展示了如何模拟JWT的主题,范围和声明。 该代码基于Spring Security 5.2.0.M3中的新功能。

Spring Security领域中的OAuth 2.0和JWT支持前景光明!

react hooks_使用Spring Cloud Gateway保护React式微服务相关推荐

  1. 使用Spring Cloud Gateway保护反应式微服务

    朋友不允许朋友写用户身份验证. 厌倦了管理自己的用户? 立即尝试Okta的API和Java SDK. 在几分钟之内即可对任何应用程序中的用户进行身份验证,管理和保护. 所以你想完全反应,是吗? 大! ...

  2. spring react_使用Spring Cloud Gateway保护React式微服务

    spring react 朋友不允许朋友写用户身份验证. 厌倦了管理自己的用户? 立即尝试Okta的API和Java SDK. 数分钟之内即可在任何应用程序中对用户进行身份验证,管理和保护. 所以你想 ...

  3. spring cloud gateway 网关_微服务网关Spring Cloud Gateway全搞定

    一.微服务网关Spring Cloud Gateway 1.1 导引 文中内容包含:微服务网关限流10万QPS.跨域.过滤器.令牌桶算法. 在构建微服务系统中,必不可少的技术就是网关了,从早期的Zuu ...

  4. Spring.Cloud.Gateway无法使用lb调用服务

    最近在使用nacos与gateway的时候,出现使用Spring.Cloud.Gateway的网关功能进行服务转发时,按照官网文档使用"lb"一直无法实现服务的调用.查了很多资料才 ...

  5. Spring Cloud Gateway整合Nacos实现服务路由及集群负载均衡

    目录 一.序言 二.代码示例 1.父工程spring-cloud-gateway-learning 2.子工程spring-cloud-api-gateway (1) pom.xml (2) 配置文件 ...

  6. spring cloud gateway监听nacos服务上下线,刷新路由,防止404

    业务场景 使用cloud gateway 作为服务网关,服务上线下线时,gateway可能会产生请求404现象 产生原因 gateway中有个缓存 CachingRouteLocator ,而网关服务 ...

  7. spring cloud构建互联网分布式微服务云平台- Netflix

    该项目通过自动配置为Spring Boot应用程序提供Netflix OSS集成,并绑定到Spring环境和其他Spring编程模型成语.通过几个简单的注释,您可以快速启用和配置应用程序中的常见模式, ...

  8. spring cloud构建互联网分布式微服务云平台-消息总线

    Spring Cloud Bus除了支持RabbitMQ的自动化配置之外,还支持现在被广泛应用的Kafka.在本文中,我们将搭建一个Kafka的本地环境,并通过它来尝试使用Spring Cloud B ...

  9. spring cloud构建互联网分布式微服务云平台-Spring Cloud Commons 普通抽象

    诸如服务发现,负载平衡和断路器之类的模式适用于所有Spring Cloud客户端可以独立于实现(例如通过Eureka或Consul发现)的消耗的共同抽象层.愿意了解源码的朋友直接求求交流分享技术一七九 ...

最新文章

  1. 带宽与码元的关系_带宽、速率(波特率、比特率)和码元宽度简述
  2. 批量操作WinRAR实用技巧七招
  3. (六)jQuery选择器
  4. OpenCV坐标体系的初步认识
  5. python多进程优化for循环_Python中for循环中的多进程处理和传递多个参数
  6. 程序编号以后计算机能够查出,华威大学研究人员开发出计算机程序,可发现量子计算机中的“泄漏”...
  7. 管理后台--3,修改分类
  8. 跨境电商erp有哪些功能?跨境erp是跨境电商卖家必备么?
  9. c#解决TCP“粘包”问题
  10. Java权限管理系统之代码实现(二)
  11. 高斯烟羽模型matlab程序,高斯烟羽模型的改进及在危化品泄漏事故模拟中的应用...
  12. 如何导出魔兽3模型到3Dmax里
  13. 用slmgr命令激活正版Win7旗舰版系统
  14. 别去赌场了,你永远赢不了“凯利公式”
  15. 用微信公众号做淘宝优惠券查券和返利机器人的详细设置教程
  16. (译)理解ConstraintLayout性能上的好处
  17. Easymock十分钟入门
  18. opencv3中的glob函数读取文件夹中数据
  19. UltraISO软碟通软件(绿色单文件版)
  20. 京东手机webapp商城

热门文章

  1. Idea 2020.1如何改变JetBrains Runtime(jbr)
  2. Flutter 自定义View之 饼状图
  3. vite引入dragula报错:global is not defined
  4. js字母大小写转换方法
  5. android gettext方法,android – getString()和getText()有什么区别?
  6. 海到无边天作岸,身登绝顶我为峰
  7. 50部经典影片,你看过哪些?
  8. 吴思《潜规则》:读圣贤书所为何事?
  9. 记录微信获取平台证书支付错误 错误的签名,验签失败
  10. 超分辨率重建生成低分辨率图像,生成降质图像公认方法代码