如何为Spring Cloud Reactive API Gateway的自定义过滤器编写单元测试,以测试它是否允许对公共端点的请求通过?

thtygnil  于 2023-01-05  发布在  Spring
关注(0)|答案(1)|浏览(124)

我正在尝试为微服务架构中的Spring Cloud Reactive API Gateway的authAccountFilter编写单元测试。网关使用WebFlux,authAccountFilter负责检查端点是公共的还是安全的。如果是公共端点,则允许请求通过。但是,如果是安全端点,则authAccountFilter在允许请求通过之前检查JWT头。
我已经尝试了多种方法和实现,但我无法通过单元测试。我怀疑问题可能与我的实现有关,但我不确定。
如果有人能提供一些指导或想法,说明如何在微服务架构中使用WebFlux为Spring Cloud Reactive API Gateway正确编写这个单元测试,我将非常感激。

网关应用程序.java:

package gateway;

import gateway.filters.*; // simplified the import all the filter once (AuthAccountFilter included)
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
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.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.server.handler.DefaultWebFilterChain;

@SpringBootApplication(exclude = { ErrorMvcAutoConfiguration.class })
@EnableEurekaClient
@CrossOrigin(origins = "*", allowedHeaders = "*")
@EnableDiscoveryClient
@EnableHystrix
public class GatewayApplication implements CommandLineRunner {

  public static void main(String[] args) {
    SpringApplication.run(GatewayApplication.class, args);
  }

  @Bean
  public RouteLocator routeLocator(RouteLocatorBuilder rlb, AuthAccountFilter authAccountFilter) {
    return rlb
        .routes()
        .route(p -> p
            .path("/my-service/**")
            .filters(f -> f
                .rewritePath("/my-service/(?<segment>.*)", "/$\\{segment}")
                .filter(authAccountFilter.apply(new AuthAccountFilter.Config())))
            .uri("lb://MY-SERVICE"))
        .build();
  }

  @Override
  public void run(String... args) throws Exception {
    System.out.println("... My-Service is UP -- READY TO GO!");
  }
}

身份验证帐户筛选器.java:

package gateway.filters;

import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.shaded.json.JSONObject;
import com.nimbusds.jwt.JWTClaimsSet;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Mono;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;

@Component
public class AuthAccountFilter extends AbstractGatewayFilterFactory<AuthAccountFilter.Config> {

  private Logger LOGGER = LoggerFactory.getLogger(AuthAccountFilter.class);

  @Autowired
  WebClient.Builder webClientBuilder;

  @Override
  public Class<Config> getConfigClass() {
    return Config.class;
  }

  public static class Config {
    // empty class as I don't need any particular configuration
  }

  @Override
  public GatewayFilter apply(Config config) {

    return (exchange, chain) -> {
      String endpoint = exchange.getRequest().getPath().toString();

      LOGGER.trace("Gateway filter for endpoint : " + endpoint);

      LOGGER.info("Checking permission for endpoint : " + endpoint);
      if (exchange.getRequest().getPath().toString().contains("auth") ||
          exchange.getRequest().getPath().toString().contains("otp") ||
          exchange.getRequest().getPath().toString().toLowerCase().contains("reset-password")) {
        LOGGER.info("Public endpoint, aborting filter");
        Mono<Void> filter = chain.filter(exchange);
        System.err.println(filter == null);
        return filter;
      }

    };
  }

}

身份验证帐户筛选器测试.java:

package gateway.filters;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.MockServerHttpResponse;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import reactor.core.CoreSubscriber;
import reactor.core.publisher.Mono;

import java.util.Arrays;

import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(SpringRunner.class)
class AuthAccountFilterTest {

  private GatewayFilterChain filterChain = mock(GatewayFilterChain.class);

  @Test
  void testPublicEndpoint() {
    String baseUrl = "http://localhost:9090/my-service/";

    // Create a mock request and response
    MockServerHttpRequest request = MockServerHttpRequest.get(baseUrl + "auth").build();
    MockServerHttpResponse response = new MockServerHttpResponse();

    // Create an instance of your AuthFilter and any dependencies it has
    AuthAccountFilter filter = new AuthAccountFilter();

    WebFilterChain chain = (exchange, filterChain) -> {
      // Set the Config instance on the Exchange object
      AuthAccountFilter.Config config = new AuthAccountFilter.Config();
      exchange.getAttributes().put("config", config);

      // Call the apply method of the AuthFilter, passing in the Config instance
      return filter.apply(config);
    };
  }
}

提前感谢您的帮助。

avwztpqn

avwztpqn1#

测试网关过滤器的最好方法可能是使用WebTestClient创建集成Sping Boot 测试,它将允许验证端到端请求处理,并确保所有配置都定义正确。
为了做到这一点,您需要通过将下游服务URI提取到配置属性中来使路由可测试。

@Bean
public RouteLocator routeLocator(RouteLocatorBuilder rlb, AuthAccountFilter authAccountFilter) {
    return rlb
            .routes()
            .route(p -> p.path("/my-service/*")
                    .filters(f -> f
                            .rewritePath("/my-service/(?<segment>.*)", "/$\\{segment}")
                            .filter(authAccountFilter.apply(new AuthAccountFilter.Config())))
                    .uri(properties.getServiceUri()))
            .build();
}

此外,还可以使用WireMock模拟下游服务并验证路由是否定义正确。

SpringBootTest(webEnvironment = RANDOM_PORT)
@AutoConfigureWireMock(port = 0) // random port
@AutoConfigureWebTestClient
class GatewayConfigurationTest {

    @Autowired
    private GatewayProperties gatewayProperties;

    @Autowired
    private WebTestClient webTestClient;

    @Test
    void verifyAuthRequest() {
        // mock downstream service
        stubFor(get(urlPathMatching("/auth"))
                .willReturn(aResponse()
                        .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                        .withStatus(200)
                )
        );

        // make request to gateway
        webTestClient
                .get()
                .uri("/my-service/auth")
                .accept(MediaType.APPLICATION_JSON)
                .exchange()
                .expectStatus().isOk();

        verify(1, getRequestedFor(urlEqualTo("/auth")));
    }

    @TestConfiguration
    static class TestGatewayConfiguration {

        public TestGatewayConfiguration(
                @Value("${wiremock.server.port}") int wireMockPort,
                GatewayProperties properties) {
            properties.setServiceUri("http://localhost:" + wireMockPort);
        }
    }
}

此测试依赖于AutoConfigureWireMock,您需要将测试依赖项添加到org.springframework.cloud:spring-cloud-contract-wiremock。作为替代方法,您可以将直接依赖项添加到WireMock并显式初始化它。
您仍然可以使用模拟请求单独使用单元测试来测试您的过滤器,但是在您的情况下,它提供的ROI非常少

@Test
void filterTest() {
    var filterFactory = new AuthAccountFilter();

    MockServerHttpRequest request = MockServerHttpRequest.get("/my-service/auth").build();
    MockServerWebExchange exchange = MockServerWebExchange.from(request);

    var filter = filterFactory.apply(new AuthAccountFilter.Config());

    GatewayFilterChain filterChain = mock(GatewayFilterChain.class);
    ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor.forClass(ServerWebExchange.class);
    when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());

    StepVerifier.create(filter.filter(exchange, filterChain))
            .verifyComplete();

    var resultExchange = captor.getValue();
    // verify result exchange
}

PS
看看Spring Security,它允许您使用SecurityWebFilterChainhttps://docs.spring.io/spring-security/reference/reactive/configuration/webflux.html定义相同的规则。

@Bean
public SecurityWebFilterChain apiSecurity(ServerHttpSecurity http) {
    http.authorizeExchange()
            .pathMatchers("/my-service/auth").permitAll()
            .pathMatchers("/my-service/otp").permitAll()
            .pathMatchers("/my-service/**/reset-password").permitAll()
            .anyExchange().authenticated()
            .and()
            .oauth2ResourceServer()
            .jwt();
    return http.build();
}

相关问题