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

The following examples show how to use org.springframework.cloud.gateway.filter.GatewayFilter. These examples are extracted from open source projects. 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 Project: spring-jwt-gateway   Source File: JWTFilter.java    License: 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 2
Source Project: spring-cloud-gateway   Source File: FilteringWebHandler.java    License: 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 3
@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 4
Source Project: tutorials   Source File: ModifyResponseGatewayFilterFactory.java    License: 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 5
@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 6
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 7
@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 8
@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 9
@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 10
@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 11
@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 12
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 13
@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 14
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 15
@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 16
@Override
public GatewayFilter apply(Object config) {
	return (exchange, chain) -> {
		ServerHttpRequest request = exchange.getRequest();

		// 不是登录请求,直接向下执行
		if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath(), SecurityConstants.OAUTH_TOKEN_URL)) {
			return chain.filter(exchange);
		}

		URI uri = exchange.getRequest().getURI();
		String queryParam = uri.getRawQuery();
		Map<String, String> paramMap = HttpUtil.decodeParamMap(queryParam, CharsetUtil.UTF_8);

		String password = paramMap.get(PASSWORD);
		if (StrUtil.isNotBlank(password)) {
			try {
				password = decryptAES(password, encodeKey);
			} catch (Exception e) {
				log.error("密码解密失败:{}", password);
				return Mono.error(e);
			}
			paramMap.put(PASSWORD, password.trim());
		}

		URI newUri = UriComponentsBuilder.fromUri(uri)
			.replaceQuery(HttpUtil.toParams(paramMap))
			.build(true)
			.toUri();

		ServerHttpRequest newRequest = exchange.getRequest().mutate().uri(newUri).build();
		return chain.filter(exchange.mutate().request(newRequest).build());
	};
}
 
Example 17
@Test
public void toStringFormat() {
	Config config = new Config().setFromHeader("myfromheader")
			.setToHeader("mytoheader");
	GatewayFilter filter = new MapRequestHeaderGatewayFilterFactory().apply(config);
	assertThat(filter.toString()).contains("myfromheader").contains("mytoheader");
}
 
Example 18
@Test
public void toStringFormat() {
	NameValueConfig config = new NameValueConfig().setName("myname")
			.setValue("myvalue");
	GatewayFilter filter = new AddResponseHeaderGatewayFilterFactory().apply(config);
	assertThat(filter.toString()).contains("myname").contains("myvalue");
}
 
Example 19
Source Project: FEBS-Cloud   Source File: FebsDocGatewayHeaderFilter.java    License: Apache License 2.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, URI)) {
            return chain.filter(exchange);
        }
        String basePath = path.substring(0, path.lastIndexOf(URI));
        ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, basePath).build();
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        return chain.filter(newExchange);
    };
}
 
Example 20
@Test
public void toStringFormat() {
	RetryConfig config = new RetryConfig();
	config.setRetries(4);
	config.setMethods(HttpMethod.GET);
	config.setSeries(HttpStatus.Series.SERVER_ERROR);
	config.setExceptions(IOException.class);
	GatewayFilter filter = new RetryGatewayFilterFactory().apply(config);
	assertThat(filter.toString()).contains("4").contains("[GET]")
			.contains("[SERVER_ERROR]").contains("[IOException]");
}
 
Example 21
@Override
public GatewayFilter apply(Config config) {
    if (log.isDebugEnabled()) {
        log.debug("Filter-{} applied", DynamicRouteGatewayFilterFactory.class.getSimpleName());
    }
    return ((exchange, chain) -> {
        log.debug("Filter-IN-{}, uri:{}", DynamicRouteGatewayFilterFactory.class.getSimpleName(),
                exchange.getRequest().getURI().toString());

        boolean enabled = config.isEnabled();

        if (!enabled) {
            return chain.filter(exchange);
        }

        Route originalRoute = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);

        if (originalRoute == null) {
            log.debug("There is none route found for filter:{}",
                    DynamicRouteGatewayFilterFactory.class.getSimpleName());
            return chain.filter(exchange);
        }

        tryPrepareDynamicRoute(exchange, originalRoute);

        try {
            return chain.filter(exchange);
        } catch (Exception e) {
            log.debug("errors while exchanging", e);
            return Mono.justOrEmpty(null);
        }
    });
}
 
Example 22
@Override
public GatewayFilter apply(Object config) {
	return (exchange, chain) -> {
		ServerHttpRequest request = exchange.getRequest();

		// 不是登录请求,直接向下执行
		if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath()
			, OAUTH_TOKEN_URL)) {
			return chain.filter(exchange);
		}

		// 刷新token,直接向下执行
		String grantType = request.getQueryParams().getFirst("grant_type");
		if (StrUtil.equals(REFRESH_TOKEN, grantType)) {
			return chain.filter(exchange);
		}

		// 终端设置不校验, 直接向下执行
		try {
			//校验验证码
			checkCode(request);
		} catch (Exception e) {
			ServerHttpResponse response = exchange.getResponse();
			response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED);
			try {
				Map map= new HashMap<>();
				map.put("code",-1);
				map.put("msg","失败");
				return response.writeWith(Mono.just(response.bufferFactory()
					.wrap(objectMapper.writeValueAsBytes(map))));
			} catch (JsonProcessingException e1) {
				log.error("对象输出异常", e1);
			}
		}

		return chain.filter(exchange);
	};
}
 
Example 23
@Test
public void toStringFormat() {
	Config config = new Config();
	config.setParts(2);
	GatewayFilter filter = new StripPrefixGatewayFilterFactory().apply(config);
	assertThat(filter.toString()).contains("2");
}
 
Example 24
@Override
public GatewayFilter apply(Tuple args) {
	return (exchange, chain) -> exchange.getSession()
		.map(webSession -> {
			log.debug("Session id: " + webSession.getId());
			webSession.getAttributes().entrySet()
				.forEach(entry ->
				log.debug(entry.getKey() + " => " +
									entry.getValue()));
			return webSession;
		})
		.map(WebSession::save)
		.then(chain.filter(exchange));
}
 
Example 25
private String getFilterClassName(GatewayFilter target) {
	if (target instanceof OrderedGatewayFilter) {
		return getFilterClassName(((OrderedGatewayFilter) target).getDelegate());
	}
	else {
		String simpleName = target.getClass().getSimpleName();
		if (StringUtils.isEmpty(simpleName)) {
			// maybe a lambda using new toString methods
			simpleName = target.toString();
		}
		return simpleName;
	}
}
 
Example 26
@Override
public GatewayFilter apply(final NameConfig config) {
    return (exchange, chain) -> {
        ServerHttpRequest originalRequest = exchange.getRequest();

        ServerHttpRequest mutatedRequest;
        if (originalRequest.getSslInfo() != null
                && ArrayUtils.isNotEmpty(originalRequest.getSslInfo().getPeerCertificates())) {

            LOG.debug("Client certificates found in original request: {}",
                    originalRequest.getSslInfo().getPeerCertificates().length);

            List<String> certs = new ArrayList<>();
            for (X509Certificate cert : originalRequest.getSslInfo().getPeerCertificates()) {
                try {
                    certs.add(Base64.getEncoder().encodeToString(cert.getEncoded()));
                } catch (CertificateEncodingException e) {
                    LOG.error("Could not encode one of client certificates", e);
                }
            }

            mutatedRequest = originalRequest.mutate().
                    headers(headers -> headers.addAll(config.getName(), certs)).
                    sslInfo(null).
                    build();
        } else {
            mutatedRequest = originalRequest;
        }

        return chain.filter(exchange.mutate().request(mutatedRequest).build());
    };
}
 
Example 27
@Test
public void toStringFormat() {
	NameValueConfig config = new NameValueConfig().setName("myname")
			.setValue("myvalue");
	GatewayFilter filter = new AddRequestHeaderGatewayFilterFactory().apply(config);
	assertThat(filter.toString()).contains("myname").contains("myvalue");
}
 
Example 28
private void testStripPrefixFilter(String actualPath, String expectedPath,
		int parts) {
	GatewayFilter filter = new StripPrefixGatewayFilterFactory()
			.apply(c -> c.setParts(parts));

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

	ServerWebExchange exchange = MockServerWebExchange.from(request);

	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);

	URI requestUrl = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(requestUrl).hasScheme("http").hasHost("localhost").hasNoPort()
			.hasPath(expectedPath);
	LinkedHashSet<URI> uris = webExchange
			.getRequiredAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
	assertThat(uris).contains(request.getURI());
}
 
Example 29
@Override
public GatewayFilter apply(final NameConfig config) {
    return (exchange, chain) -> exchange.getSession().
            flatMap(session -> Mono.justOrEmpty(Optional.ofNullable(
            cacheManager.getCache(SessionConfig.DEFAULT_CACHE).get(session.getId(), Session.class)).
            map(cachedSession -> {
                String principal = null;

                SecurityContext ctx = cachedSession.getAttribute(
                        WebSessionServerSecurityContextRepository.DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME);
                if (ctx != null && ctx.getAuthentication() != null) {
                    if (ctx.getAuthentication().getPrincipal() instanceof OidcUser) {
                        principal = ((OidcUser) ctx.getAuthentication().getPrincipal()).
                                getIdToken().getTokenValue();
                    } else if (ctx.getAuthentication().getPrincipal() instanceof OAuth2User) {
                        principal = Objects.toString(((OAuth2User) ctx.getAuthentication().getPrincipal()).
                                getAttributes().get(StandardClaimNames.PREFERRED_USERNAME), null);
                    } else {
                        principal = ctx.getAuthentication().getName();
                    }
                }

                return principal;
            }))).
            transform(principal -> principal.flatMap(p -> StringUtils.isEmpty(p)
            ? chain.filter(exchange)
            : chain.filter(exchange.mutate().
                    request(exchange.getRequest().mutate().
                            headers(headers -> headers.add(config.getName(), p)).build()).
                    build()))).
            switchIfEmpty(chain.filter(exchange));
}
 
Example 30
@Override
public GatewayFilter apply(Config config) {
	ModifyResponseGatewayFilter gatewayFilter = new ModifyResponseGatewayFilter(
			config);
	gatewayFilter.setFactory(this);
	return gatewayFilter;
}