org.springframework.cloud.gateway.filter.GatewayFilter Java Examples

The following examples show how to use org.springframework.cloud.gateway.filter.GatewayFilter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FilteringWebHandler.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange exchange) {
	Route route = exchange.getRequiredAttribute(GATEWAY_ROUTE_ATTR);
	List<GatewayFilter> gatewayFilters = route.getFilters();

	List<GatewayFilter> combined = new ArrayList<>(this.globalFilters);
	combined.addAll(gatewayFilters);
	// TODO: needed or cached?
	AnnotationAwareOrderComparator.sort(combined);

	if (logger.isDebugEnabled()) {
		logger.debug("Sorted gatewayFilterFactories: " + combined);
	}

	return new DefaultGatewayFilterChain(combined).filter(exchange);
}
 
Example #2
Source File: RouteDefinitionRouteLocator.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private List<GatewayFilter> getFilters(RouteDefinition routeDefinition) {
	List<GatewayFilter> filters = new ArrayList<>();

	// TODO: support option to apply defaults after route specific filters?
	if (!this.gatewayProperties.getDefaultFilters().isEmpty()) {
		filters.addAll(loadGatewayFilters(DEFAULT_FILTERS,
				new ArrayList<>(this.gatewayProperties.getDefaultFilters())));
	}

	if (!routeDefinition.getFilters().isEmpty()) {
		filters.addAll(loadGatewayFilters(routeDefinition.getId(),
				new ArrayList<>(routeDefinition.getFilters())));
	}

	AnnotationAwareOrderComparator.sort(filters);
	return filters;
}
 
Example #3
Source File: JWTFilter.java    From spring-jwt-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public GatewayFilter apply(NameValueConfig config) {
    return (exchange, chain) -> {

        try {
            String token = this.extractJWTToken(exchange.getRequest());
            DecodedJWT decodedJWT = this.jwtVerifier.verify(token);

            ServerHttpRequest request = exchange.getRequest().mutate().
                    header(X_JWT_SUB_HEADER, decodedJWT.getSubject()).
                    build();

            return chain.filter(exchange.mutate().request(request).build());

        } catch (JWTVerificationException ex) {

            logger.error(ex.toString());
            return this.onError(exchange, ex.getMessage());
        }
    };
}
 
Example #4
Source File: DedupeResponseHeaderGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public GatewayFilter apply(Config config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			return chain.filter(exchange).then(Mono.fromRunnable(
					() -> dedupe(exchange.getResponse().getHeaders(), config)));
		}

		@Override
		public String toString() {
			return filterToStringCreator(
					DedupeResponseHeaderGatewayFilterFactory.this)
							.append(config.getName(), config.getStrategy())
							.toString();
		}
	};
}
 
Example #5
Source File: PreserveHostHeaderGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
public GatewayFilter apply(Object config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			exchange.getAttributes().put(PRESERVE_HOST_HEADER_ATTRIBUTE, true);
			return chain.filter(exchange);
		}

		@Override
		public String toString() {
			return filterToStringCreator(PreserveHostHeaderGatewayFilterFactory.this)
					.toString();
		}
	};
}
 
Example #6
Source File: RewriteLocationResponseHeaderGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public GatewayFilter apply(Config config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			return chain.filter(exchange)
					.then(Mono.fromRunnable(() -> rewriteLocation(exchange, config)));
		}

		@Override
		public String toString() {
			// @formatter:off
			return filterToStringCreator(
					RewriteLocationResponseHeaderGatewayFilterFactory.this)
					.append("stripVersion", config.stripVersion)
					.append("locationHeaderName", config.locationHeaderName)
					.append("hostValue", config.hostValue)
					.append("protocols", config.protocols)
					.toString();
			// @formatter:on
		}
	};
}
 
Example #7
Source File: SetResponseHeaderGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public GatewayFilter apply(NameValueConfig config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
			return chain.filter(exchange).then(Mono.fromRunnable(() -> exchange
					.getResponse().getHeaders().set(config.name, value)));
		}

		@Override
		public String toString() {
			return filterToStringCreator(SetResponseHeaderGatewayFilterFactory.this)
					.append(config.getName(), config.getValue()).toString();
		}
	};
}
 
Example #8
Source File: ModifyResponseGatewayFilterFactory.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public GatewayFilter apply(Config config) {
    return (exchange, chain) -> {
        return chain.filter(exchange)
            .then(Mono.fromRunnable(() -> {
                ServerHttpResponse response = exchange.getResponse();

                Optional.ofNullable(exchange.getRequest()
                    .getQueryParams()
                    .getFirst("locale"))
                    .ifPresent(qp -> {
                        String responseContentLanguage = response.getHeaders()
                            .getContentLanguage()
                            .getLanguage();

                        response.getHeaders()
                            .add("Bael-Custom-Language-Header", responseContentLanguage);
                        logger.info("Added custom header to Response");
                    });
            }));
    };
}
 
Example #9
Source File: RequestHeaderToRequestUriGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void filterDoesNotChangeRequestUriIfHeaderIsAbsent() {
	RequestHeaderToRequestUriGatewayFilterFactory factory = new RequestHeaderToRequestUriGatewayFilterFactory();
	GatewayFilter filter = factory.apply(c -> c.setName("X-CF-Forwarded-Url"));
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.build();
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR,
			URI.create("http://localhost"));
	GatewayFilterChain filterChain = mock(GatewayFilterChain.class);
	ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor
			.forClass(ServerWebExchange.class);
	when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());
	filter.filter(exchange, filterChain);
	ServerWebExchange webExchange = captor.getValue();
	URI uri = (URI) webExchange.getAttributes().get(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).isNotNull();
	assertThat(uri.toString()).isEqualTo("http://localhost");
}
 
Example #10
Source File: RemoveRequestParameterGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void removeRequestParameterFilterShouldHandleRemainingParamsWhichRequiringEncoding() {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.queryParam("foo", "bar").queryParam("aaa", "abc xyz")
			.queryParam("bbb", "[xyz").queryParam("ccc", ",xyz").build();
	exchange = MockServerWebExchange.from(request);
	NameConfig config = new NameConfig();
	config.setName("foo");
	GatewayFilter filter = new RemoveRequestParameterGatewayFilterFactory()
			.apply(config);

	filter.filter(exchange, filterChain);

	ServerHttpRequest actualRequest = captor.getValue().getRequest();
	assertThat(actualRequest.getQueryParams()).doesNotContainKey("foo");
	assertThat(actualRequest.getQueryParams()).containsEntry("aaa",
			singletonList("abc xyz"));
	assertThat(actualRequest.getQueryParams()).containsEntry("bbb",
			singletonList("[xyz"));
	assertThat(actualRequest.getQueryParams()).containsEntry("ccc",
			singletonList(",xyz"));
}
 
Example #11
Source File: SaveSessionGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public GatewayFilter apply(Object config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			return exchange.getSession().map(WebSession::save)
					.then(chain.filter(exchange));
		}

		@Override
		public String toString() {
			return filterToStringCreator(SaveSessionGatewayFilterFactory.this)
					.toString();
		}
	};
}
 
Example #12
Source File: SetPathGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private void testFilter(String template, String expectedPath,
		HashMap<String, String> variables) {
	GatewayFilter filter = new SetPathGatewayFilterFactory()
			.apply(c -> c.setTemplate(template));

	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.build();

	ServerWebExchange exchange = MockServerWebExchange.from(request);
	ServerWebExchangeUtils.putUriTemplateVariables(exchange, variables);

	GatewayFilterChain filterChain = mock(GatewayFilterChain.class);

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

	filter.filter(exchange, filterChain);

	ServerWebExchange webExchange = captor.getValue();

	assertThat(webExchange.getRequest().getURI()).hasPath(expectedPath);
	LinkedHashSet<URI> uris = webExchange
			.getRequiredAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
	assertThat(uris).contains(request.getURI());
}
 
Example #13
Source File: RemoveRequestHeaderGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public GatewayFilter apply(NameConfig config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			ServerHttpRequest request = exchange.getRequest().mutate()
					.headers(httpHeaders -> httpHeaders.remove(config.getName()))
					.build();

			return chain.filter(exchange.mutate().request(request).build());
		}

		@Override
		public String toString() {
			return filterToStringCreator(RemoveRequestHeaderGatewayFilterFactory.this)
					.append("name", config.getName()).toString();
		}
	};
}
 
Example #14
Source File: RewriteResponseHeaderGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public GatewayFilter apply(Config config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			return chain.filter(exchange)
					.then(Mono.fromRunnable(() -> rewriteHeader(exchange, config)));
		}

		@Override
		public String toString() {
			return filterToStringCreator(
					RewriteResponseHeaderGatewayFilterFactory.this)
							.append("name", config.getName())
							.append("regexp", config.getRegexp())
							.append("replacement", config.getReplacement())
							.toString();
		}
	};
}
 
Example #15
Source File: ModifyResponseBodyGatewayFilterFactoryUnitTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringFormat() {
	Config config = new Config();
	config.setInClass(String.class);
	config.setOutClass(Integer.class);
	config.setNewContentType("mycontenttype");
	GatewayFilter filter = new ModifyResponseBodyGatewayFilterFactory(
			new DefaultServerCodecConfigurer().getReaders(), emptySet(), emptySet())
					.apply(config);
	assertThat(filter.toString()).contains("String").contains("Integer")
			.contains("mycontenttype");
}
 
Example #16
Source File: ModifyRequestBodyGatewayFilterFactoryUnitTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringFormat() {
	Config config = new Config();
	config.setInClass(String.class);
	config.setOutClass(Integer.class);
	config.setContentType("mycontenttype");
	GatewayFilter filter = new ModifyRequestBodyGatewayFilterFactory().apply(config);
	assertThat(filter.toString()).contains("String").contains("Integer")
			.contains("mycontenttype");
}
 
Example #17
Source File: Route.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
private Route(String id, URI uri, int order,
		AsyncPredicate<ServerWebExchange> predicate,
		List<GatewayFilter> gatewayFilters, Map<String, Object> metadata) {
	this.id = id;
	this.uri = uri;
	this.order = order;
	this.predicate = predicate;
	this.gatewayFilters = gatewayFilters;
	this.metadata = metadata;
}
 
Example #18
Source File: ChainRequestGatewayFilterFactory.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public GatewayFilter apply(Config config) {
    return (exchange, chain) -> {
        return client.get()
            .uri(config.getLanguageServiceEndpoint())
            .exchange()
            .flatMap(response -> {
                return (response.statusCode()
                    .is2xxSuccessful()) ? response.bodyToMono(String.class) : Mono.just(config.getDefaultLanguage());
            })
            .map(LanguageRange::parse)
            .map(range -> {
                exchange.getRequest()
                    .mutate()
                    .headers(h -> h.setAcceptLanguage(range));

                String allOutgoingRequestLanguages = exchange.getRequest()
                    .getHeaders()
                    .getAcceptLanguage()
                    .stream()
                    .map(r -> r.getRange())
                    .collect(Collectors.joining(","));

                logger.info("Chain Request output - Request contains Accept-Language header: " + allOutgoingRequestLanguages);

                return exchange;
            })
            .flatMap(chain::filter);

    };
}
 
Example #19
Source File: PrefixPathGatewayFilterFactoryTest.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringFormat() {
	Config config = new Config();
	config.setPrefix("myprefix");
	GatewayFilter filter = new PrefixPathGatewayFilterFactory().apply(config);
	assertThat(filter.toString()).contains("myprefix");
}
 
Example #20
Source File: GatewayFilterSpec.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
public List<GatewayFilter> transformToOrderedFilters(Stream<GatewayFilter> stream) {
	return stream.map(filter -> {
		if (filter instanceof Ordered) {
			return filter;
		}
		else {
			return new OrderedGatewayFilter(filter, 0);
		}
	}).collect(Collectors.toList());
}
 
Example #21
Source File: RedirectToGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
public GatewayFilter apply(String statusString, String urlString) {
	HttpStatusHolder httpStatus = HttpStatusHolder.parse(statusString);
	Assert.isTrue(httpStatus.is3xxRedirection(),
			"status must be a 3xx code, but was " + statusString);
	final URI url = URI.create(urlString);
	return apply(httpStatus, url);
}
 
Example #22
Source File: LoggingGatewayFilterFactory.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public GatewayFilter apply(Config config) {
    return new OrderedGatewayFilter((exchange, chain) -> {
        if (config.isPreLogger())
            logger.info("Pre GatewayFilter logging: " + config.getBaseMessage());
        return chain.filter(exchange)
            .then(Mono.fromRunnable(() -> {
                if (config.isPostLogger())
                    logger.info("Post GatewayFilter logging: " + config.getBaseMessage());
            }));
    }, 1);
}
 
Example #23
Source File: RewriteResponseHeaderGatewayFilterFactoryUnitTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringFormat() {
	Config config = new Config();
	config.setName("myname");
	config.setRegexp("myregexp");
	config.setReplacement("myreplacement");
	GatewayFilter filter = new RewriteResponseHeaderGatewayFilterFactory()
			.apply(config);
	assertThat(filter.toString()).contains("myname").contains("myregexp")
			.contains("myreplacement");
}
 
Example #24
Source File: RouteDefinitionRouteLocatorTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() {
	List<RoutePredicateFactory> predicates = Arrays
			.asList(new HostRoutePredicateFactory());
	List<GatewayFilterFactory> gatewayFilterFactories = Arrays.asList(
			new RemoveResponseHeaderGatewayFilterFactory(),
			new AddResponseHeaderGatewayFilterFactory(),
			new TestOrderedGatewayFilterFactory());
	GatewayProperties gatewayProperties = new GatewayProperties();
	gatewayProperties.setRoutes(Arrays.asList(new RouteDefinition() {
		{
			setId("foo");
			setUri(URI.create("https://foo.example.com"));
			setPredicates(
					Arrays.asList(new PredicateDefinition("Host=*.example.com")));
			setFilters(Arrays.asList(
					new FilterDefinition("RemoveResponseHeader=Server"),
					new FilterDefinition("TestOrdered="),
					new FilterDefinition("AddResponseHeader=X-Response-Foo, Bar")));
		}
	}));

	PropertiesRouteDefinitionLocator routeDefinitionLocator = new PropertiesRouteDefinitionLocator(
			gatewayProperties);
	@SuppressWarnings("deprecation")
	RouteDefinitionRouteLocator routeDefinitionRouteLocator = new RouteDefinitionRouteLocator(
			new CompositeRouteDefinitionLocator(Flux.just(routeDefinitionLocator)),
			predicates, gatewayFilterFactories, gatewayProperties,
			new ConfigurationService(null, () -> null, () -> null));

	StepVerifier.create(routeDefinitionRouteLocator.getRoutes()).assertNext(route -> {
		List<GatewayFilter> filters = route.getFilters();
		assertThat(filters).hasSize(3);
		assertThat(getFilterClassName(filters.get(0)))
				.contains("RemoveResponseHeader");
		assertThat(getFilterClassName(filters.get(1))).contains("AddResponseHeader");
		assertThat(getFilterClassName(filters.get(2)))
				.contains("RouteDefinitionRouteLocatorTests$TestOrderedGateway");
	}).expectComplete().verify();
}
 
Example #25
Source File: RemoveResponseHeaderGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringFormat() {
	NameConfig config = new NameConfig();
	config.setName("myname");
	GatewayFilter filter = new RemoveResponseHeaderGatewayFilterFactory()
			.apply(config);
	assertThat(filter.toString()).contains("myname");
}
 
Example #26
Source File: RemoveRequestParameterGatewayFilterFactoryIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringFormat() {
	NameConfig config = new NameConfig();
	config.setName("myname");
	GatewayFilter filter = new RemoveRequestParameterGatewayFilterFactory()
			.apply(config);
	assertThat(filter.toString()).contains("myname");
}
 
Example #27
Source File: RetryGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
public GatewayFilter apply(String routeId, Repeat<ServerWebExchange> repeat,
		Retry<ServerWebExchange> retry) {
	if (routeId != null && getPublisher() != null) {
		// send an event to enable caching
		getPublisher().publishEvent(new EnableBodyCachingEvent(this, routeId));
	}
	return (exchange, chain) -> {
		trace("Entering retry-filter");

		// chain.filter returns a Mono<Void>
		Publisher<Void> publisher = chain.filter(exchange)
				// .log("retry-filter", Level.INFO)
				.doOnSuccess(aVoid -> updateIteration(exchange))
				.doOnError(throwable -> updateIteration(exchange));

		if (retry != null) {
			// retryWhen returns a Mono<Void>
			// retry needs to go before repeat
			publisher = ((Mono<Void>) publisher)
					.retryWhen(retry.withApplicationContext(exchange));
		}
		if (repeat != null) {
			// repeatWhen returns a Flux<Void>
			// so this needs to be last and the variable a Publisher<Void>
			publisher = ((Mono<Void>) publisher)
					.repeatWhen(repeat.withApplicationContext(exchange));
		}

		return Mono.fromDirect(publisher);
	};
}
 
Example #28
Source File: RequestSizeGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public GatewayFilter apply(
		RequestSizeGatewayFilterFactory.RequestSizeConfig requestSizeConfig) {
	requestSizeConfig.validate();
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			ServerHttpRequest request = exchange.getRequest();
			String contentLength = request.getHeaders().getFirst("content-length");
			if (!StringUtils.isEmpty(contentLength)) {
				Long currentRequestSize = Long.valueOf(contentLength);
				if (currentRequestSize > requestSizeConfig.getMaxSize().toBytes()) {
					exchange.getResponse()
							.setStatusCode(HttpStatus.PAYLOAD_TOO_LARGE);
					if (!exchange.getResponse().isCommitted()) {
						exchange.getResponse().getHeaders().add("errorMessage",
								getErrorMessage(currentRequestSize,
										requestSizeConfig.getMaxSize().toBytes()));
					}
					return exchange.getResponse().setComplete();
				}
			}
			return chain.filter(exchange);
		}

		@Override
		public String toString() {
			return filterToStringCreator(RequestSizeGatewayFilterFactory.this)
					.append("max", requestSizeConfig.getMaxSize()).toString();
		}
	};
}
 
Example #29
Source File: SwaggerHeaderFilter.java    From smaker with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public GatewayFilter apply(Object config) {
    return (exchange, chain) -> {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (!StringUtils.endsWithIgnoreCase(path, GatewaySwaggerProvider.SWAGGER2URL)) {
            return chain.filter(exchange);
        }
        String basePath = path.substring(0, path.lastIndexOf(GatewaySwaggerProvider.SWAGGER2URL));
        ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, basePath).build();
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        return chain.filter(newExchange);
    };
}
 
Example #30
Source File: GatewayFilterSpec.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
/**
 * Applies the filter to the route.
 * @param gatewayFilter the filter to apply
 * @return a {@link GatewayFilterSpec} that can be used to apply additional filters
 */
public GatewayFilterSpec filter(GatewayFilter gatewayFilter) {
	if (gatewayFilter instanceof Ordered) {
		this.routeBuilder.filter(gatewayFilter);
		return this;
	}
	return this.filter(gatewayFilter, 0);
}