Java Code Examples for org.springframework.cloud.gateway.filter.GatewayFilterChain#filter()

The following examples show how to use org.springframework.cloud.gateway.filter.GatewayFilterChain#filter() . 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: AddRequestHeaderGatewayFilterFactory.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());
			ServerHttpRequest request = exchange.getRequest().mutate()
					.header(config.getName(), value).build();

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

		@Override
		public String toString() {
			return filterToStringCreator(AddRequestHeaderGatewayFilterFactory.this)
					.append(config.getName(), config.getValue()).toString();
		}
	};
}
 
Example 2
Source File: AuthFilter.java    From SpringBlade with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	String path = exchange.getRequest().getURI().getPath();
	if (isSkip(path)) {
		return chain.filter(exchange);
	}
	ServerHttpResponse resp = exchange.getResponse();
	String headerToken = exchange.getRequest().getHeaders().getFirst(AuthProvider.AUTH_KEY);
	String paramToken = exchange.getRequest().getQueryParams().getFirst(AuthProvider.AUTH_KEY);
	if (StringUtils.isAllBlank(headerToken, paramToken)) {
		return unAuth(resp, "缺失令牌,鉴权失败");
	}
	String auth = StringUtils.isBlank(headerToken) ? paramToken : headerToken;
	String token = JwtUtil.getToken(auth);
	Claims claims = JwtUtil.parseJWT(token);
	if (claims == null) {
		return unAuth(resp, "请求未授权");
	}
	return chain.filter(exchange);
}
 
Example 3
Source File: CorsFilter.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, GatewayFilterChain chain) {
    ServerHttpRequest request = serverWebExchange.getRequest();
    ServerHttpResponse response = serverWebExchange.getResponse();
    HttpHeaders headers = response.getHeaders();
    headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, PUT, OPTIONS, DELETE, PATCH");
    headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*");
    headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL);
    headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
    if (request.getMethod() == HttpMethod.OPTIONS) {
        response.setStatusCode(HttpStatus.OK);
        return Mono.empty();
    }
    return chain.filter(serverWebExchange);
}
 
Example 4
Source File: DecodePasswordFilter.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    // 当前请求
    ServerHttpRequest request = exchange.getRequest();
    // 请求的URI
    URI uri = request.getURI();
    // 获取token的请求
    if (HttpMethod.POST.matches(request.getMethodValue()) && StrUtil.containsAnyIgnoreCase(uri.getPath(), GatewayConstant.OAUTH_TOKEN_URL, GatewayConstant.REGISTER,
            GatewayConstant.MOBILE_TOKEN_URL)) {
        String grantType = request.getQueryParams().getFirst(GatewayConstant.GRANT_TYPE);
        // 授权类型为密码模式则解密
        if (CommonConstant.GRANT_TYPE_PASSWORD.equals(grantType) || StrUtil.containsAnyIgnoreCase(uri.getPath(), GatewayConstant.REGISTER)) {
            String credential = request.getQueryParams().getFirst(CREDENTIAL);
            if (StringUtils.isNotBlank(credential)) {
                try {
                    // 开始解密
                    credential = AesUtil.decryptAES(credential, sysProperties.getKey());
                    credential = credential.trim();
                } catch (Exception e) {
                    log.error("credential decrypt fail:{}", credential);
                }
                URI newUri = UriComponentsBuilder.fromUri(uri)
                        // 替换password字段
                        .replaceQueryParam(PASSWORD, credential)
                        // 替换credential字段
                        .replaceQueryParam(CREDENTIAL, credential)
                        .build(true).toUri();
                request = request.mutate().uri(newUri).build();
                return chain.filter(exchange.mutate().request(request).build());
            }
        }
    }
    return chain.filter(exchange);
}
 
Example 5
Source File: StripPrefixGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public GatewayFilter apply(Config config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			ServerHttpRequest request = exchange.getRequest();
			addOriginalRequestUrl(exchange, request.getURI());
			String path = request.getURI().getRawPath();
			String newPath = "/"
					+ Arrays.stream(StringUtils.tokenizeToStringArray(path, "/"))
							.skip(config.parts).collect(Collectors.joining("/"));
			newPath += (newPath.length() > 1 && path.endsWith("/") ? "/" : "");
			ServerHttpRequest newRequest = request.mutate().path(newPath).build();

			exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR,
					newRequest.getURI());

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

		@Override
		public String toString() {
			return filterToStringCreator(StripPrefixGatewayFilterFactory.this)
					.append("parts", config.getParts()).toString();
		}
	};
}
 
Example 6
Source File: GatewayNoLoadBalancerClientAutoConfiguration.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("Duplicates")
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	URI url = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
	String schemePrefix = exchange.getAttribute(GATEWAY_SCHEME_PREFIX_ATTR);
	if (url == null
			|| (!"lb".equals(url.getScheme()) && !"lb".equals(schemePrefix))) {
		return chain.filter(exchange);
	}

	throw NotFoundException.create(use404,
			"Unable to find instance for " + url.getHost());
}
 
Example 7
Source File: AuthFilter.java    From hello-spring-cloud-alibaba with MIT License 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    String token = exchange.getRequest().getQueryParams().getFirst("token");

    if (token == null || token.isEmpty()) {
        ServerHttpResponse response = exchange.getResponse();

        // 封装错误信息
        Map<String, Object> responseData = Maps.newHashMap();
        responseData.put("code", 401);
        responseData.put("message", "非法请求");
        responseData.put("cause", "Token is empty");

        try {
            // 将信息转换为 JSON
            ObjectMapper objectMapper = new ObjectMapper();
            byte[] data = objectMapper.writeValueAsBytes(responseData);

            // 输出错误信息到页面
            DataBuffer buffer = response.bufferFactory().wrap(data);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            log.error("{}", e);
        }
    }

    return chain.filter(exchange);
}
 
Example 8
Source File: Fix302GlobalFilter.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    URI requestUri = exchange.getRequest().getURI();
    ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(exchange.getResponse()) {
        @Override
        public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
            switch (getStatusCode()) {
                case MOVED_PERMANENTLY: //301
                case FOUND: //302
                    HttpHeaders headers = getHeaders();
                    String location = headers.getFirst(HttpHeaders.LOCATION);
                    if (!StringUtils.isEmpty(location)) {
                        UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl(location);
                        // replace scheme//host:port with original request's
                        uriComponentsBuilder.scheme(requestUri.getScheme())
                                .host(requestUri.getHost())
                                .port(requestUri.getPort());
                        String newLocation = uriComponentsBuilder.build().toUri().toString();
                        headers.put(HttpHeaders.LOCATION, Collections.singletonList(newLocation));

                        log.info("301/302 redirect in R: {}, FIX location {} -> {}", requestUri, location, newLocation);
                    }
                    break;

                default:
                    break;
            }

            return super.writeWith(body);
        }
    };

    // replace response with decorator
    return chain.filter(exchange.mutate().response(decoratedResponse).build());
}
 
Example 9
Source File: AuthorizeFilter.java    From spring-cloud-microservice with MIT License 5 votes vote down vote up
/**
 * 全局过滤教研token,生产环境可以用数据库
 *
 * @param exchange
 * @param chain
 * @return
 */
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    HttpHeaders headers = request.getHeaders();
    String token = headers.getFirst(AUTHORIZE_TOKEN);
    String uid = headers.getFirst(AUTHORIZE_UID);
    if (token == null) {
        token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
    }
    if (uid == null) {
        uid = request.getQueryParams().getFirst(AUTHORIZE_UID);
    }

    ServerHttpResponse response = exchange.getResponse();
    if (StringUtils.isEmpty(token) || StringUtils.isEmpty(uid)) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
    String authToken = stringRedisTemplate.opsForValue().get(uid);
    if (authToken == null || !authToken.equals(token)) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    return chain.filter(exchange);
}
 
Example 10
Source File: RequestStatisticsFilter.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    Map<String, String> headers = request.getHeaders().toSingleValueMap();
    UserAgent userAgent = UserAgent.parseUserAgentString(headers.get("User-Agent"));
    //埋点
    PointUtil.debug("1", "request-statistics",
            "ip=" + ReactiveAddrUtil.getRemoteAddr(request)
                    + "&browser=" + getBrowser(userAgent.getBrowser().name())
                    + "&operatingSystem=" + getOperatingSystem(userAgent.getOperatingSystem().name()));

    return chain.filter(exchange);
}
 
Example 11
Source File: BaseWebClientTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	if (exchange.getRequest().getPath().toString().contains("httpbin/httpbin")) {
		return Mono
				.error(new IllegalStateException("recursive call to /httpbin"));
	}
	return chain.filter(exchange);
}
 
Example 12
Source File: RemoveRequestParameterGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 5 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();
			MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>(
					request.getQueryParams());
			queryParams.remove(config.getName());

			URI newUri = UriComponentsBuilder.fromUri(request.getURI())
					.replaceQueryParams(unmodifiableMultiValueMap(queryParams))
					.build().toUri();

			ServerHttpRequest updatedRequest = exchange.getRequest().mutate()
					.uri(newUri).build();

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

		@Override
		public String toString() {
			return filterToStringCreator(
					RemoveRequestParameterGatewayFilterFactory.this)
							.append("name", config.getName()).toString();
		}
	};
}
 
Example 13
Source File: WrapperResponseFilter.java    From gateway with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 响应消息输出过滤器
 *
 * @param exchange ServerWebExchange
 * @param chain    GatewayFilterChain
 * @return Mono
 */
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpResponse originalResponse = exchange.getResponse();
    ServerHttpResponseDecorator responseDecorator = new ServerHttpResponseDecorator(originalResponse) {

        @Override
        public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
            Boolean logResult = exchange.getAttribute("logResult");
            if (logResult == null || !logResult) {
                return super.writeWith(body);
            }

            if (body instanceof Flux) {
                Flux<? extends DataBuffer> fluxBody = Flux.from(body);

                return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                    List<String> list = new ArrayList<>();
                    dataBuffers.forEach(dataBuffer -> {
                        byte[] content = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(content);
                        DataBufferUtils.release(dataBuffer);
                        list.add(new String(content, StandardCharsets.UTF_8));
                    });

                    String json = String.join("", list);
                    logger.info("返回数据: {}", json);

                    return bufferFactory().wrap(json.getBytes());
                }));
            }

            return super.writeWith(body);
        }
    };
    // replace response with decorator
    return chain.filter(exchange.mutate().response(responseDecorator).build());
}
 
Example 14
Source File: ThrottleGatewayFilterFactory.java    From microservice-integration with MIT License 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

    //TODO: get a token bucket for a key
    log.debug("TokenBucket capacity: " + tokenBucket.getCapacity());
    boolean consumed = tokenBucket.tryConsume();
    if (consumed) {
        return chain.filter(exchange);
    }
    exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
    return exchange.getResponse().setComplete();
}
 
Example 15
Source File: AuthFilter.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    exchange.getResponse().setStatusCode(HttpStatus.OK);
    exchange.getResponse().getHeaders().add("Content-Type", "application/json;charset=UTF-8");
    System.out.println(exchange.getRequest().getURI());
    return chain.filter(exchange);
}
 
Example 16
Source File: SetPathGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public GatewayFilter apply(Config config) {
	UriTemplate uriTemplate = new UriTemplate(config.template);

	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			ServerHttpRequest req = exchange.getRequest();
			addOriginalRequestUrl(exchange, req.getURI());

			Map<String, String> uriVariables = getUriTemplateVariables(exchange);

			URI uri = uriTemplate.expand(uriVariables);
			String newPath = uri.getRawPath();

			exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri);

			ServerHttpRequest request = req.mutate().path(newPath).build();

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

		@Override
		public String toString() {
			return filterToStringCreator(SetPathGatewayFilterFactory.this)
					.append("template", config.getTemplate()).toString();
		}
	};
}
 
Example 17
Source File: AuthFilter.java    From codeway_service with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	exchange.getResponse().setStatusCode(HttpStatus.OK);
	exchange.getResponse().getHeaders().add("Content-Type", "application/json;charset=UTF-8");
	JsonData result = new JsonData();
	//后端调用跳过验签
	boolean skipAuth = Boolean.valueOf(exchange.getRequest().getQueryParams().getFirst("skipAuth"));
	if (!skipAuth) {
		String sign = exchange.getRequest().getQueryParams().getFirst("sign");
		if (StringUtils.isEmpty(sign)) {
			//没有验签参数
			result.setCode(3333);
			result.setMessage("没有验签参数");
			return exchange.getResponse().writeWith(Flux.just(this.getBodyBuffer(exchange.getResponse(), result)));
		}
		String publicKey = exchange.getRequest().getHeaders().getFirst("publicKey");
		if (StringUtils.isEmpty(publicKey)) {
			//没有公钥
			result.setCode(2222);
			result.setMessage("没有公钥");
			return exchange.getResponse().writeWith(Flux.just(this.getBodyBuffer(exchange.getResponse(), result)));
		}
		String privateKey = (String) redisService.get(publicKey);
		if (!StringUtils.isEmpty(privateKey)) {
			TreeMap<String, List<String>> parameterMap = new TreeMap<>(exchange.getRequest().getQueryParams());
			//验签
			StringBuilder sb = new StringBuilder();
			parameterMap.entrySet().forEach(stringEntry -> {
				if (!StringUtils.equalsIgnoreCase(stringEntry.getKey(), "sign")) {
					if (!CollectionUtils.isEmpty(stringEntry.getValue())) {
						sb.append(stringEntry.getKey());
						sb.append("=");
						sb.append(stringEntry.getValue().stream().findFirst().get());
					}
				}
			});
			sb.append("privateKey=");
			sb.append(privateKey);
			System.out.println(sb.toString());
			String serverSign = DigestUtils.md5Hex(sb.toString());
			System.out.println(serverSign);
			if (!serverSign.equals(sign)) {
				//验签不通过
				result.setCode(0000);
				result.setMessage("验签不通过");
				return exchange.getResponse().writeWith(Flux.just(this.getBodyBuffer(exchange.getResponse(), result)));
			}
		} else {
			//私钥过期
			result.setCode(1111);
			result.setMessage("私钥过期");
			return exchange.getResponse().writeWith(Flux.just(this.getBodyBuffer(exchange.getResponse(), result)));
		}
	}
	return chain.filter(exchange);
}
 
Example 18
Source File: ModifyResponseBodyGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	return chain.filter(exchange.mutate()
			.response(new ModifiedServerHttpResponse(exchange, config)).build());
}
 
Example 19
Source File: SecureHeadersGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@Override
public GatewayFilter apply(Object config) {
	// TODO: allow args to override properties

	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			HttpHeaders headers = exchange.getResponse().getHeaders();

			List<String> disabled = properties.getDisable();

			if (isEnabled(disabled, X_XSS_PROTECTION_HEADER)) {
				headers.add(X_XSS_PROTECTION_HEADER,
						properties.getXssProtectionHeader());
			}

			if (isEnabled(disabled, STRICT_TRANSPORT_SECURITY_HEADER)) {
				headers.add(STRICT_TRANSPORT_SECURITY_HEADER,
						properties.getStrictTransportSecurity());
			}

			if (isEnabled(disabled, X_FRAME_OPTIONS_HEADER)) {
				headers.add(X_FRAME_OPTIONS_HEADER, properties.getFrameOptions());
			}

			if (isEnabled(disabled, X_CONTENT_TYPE_OPTIONS_HEADER)) {
				headers.add(X_CONTENT_TYPE_OPTIONS_HEADER,
						properties.getContentTypeOptions());
			}

			if (isEnabled(disabled, REFERRER_POLICY_HEADER)) {
				headers.add(REFERRER_POLICY_HEADER, properties.getReferrerPolicy());
			}

			if (isEnabled(disabled, CONTENT_SECURITY_POLICY_HEADER)) {
				headers.add(CONTENT_SECURITY_POLICY_HEADER,
						properties.getContentSecurityPolicy());
			}

			if (isEnabled(disabled, X_DOWNLOAD_OPTIONS_HEADER)) {
				headers.add(X_DOWNLOAD_OPTIONS_HEADER,
						properties.getDownloadOptions());
			}

			if (isEnabled(disabled, X_PERMITTED_CROSS_DOMAIN_POLICIES_HEADER)) {
				headers.add(X_PERMITTED_CROSS_DOMAIN_POLICIES_HEADER,
						properties.getPermittedCrossDomainPolicies());
			}

			return chain.filter(exchange);
		}

		@Override
		public String toString() {
			return filterToStringCreator(SecureHeadersGatewayFilterFactory.this)
					.toString();
		}
	};
}
 
Example 20
Source File: AuthFilter.java    From light-reading-cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    // 白名单Path
    Set<String> whiteList = this.getWhiteList();
    String path = exchange.getRequest().getPath().toString();

    // 主页接口、图书接口正则匹配
    boolean indexMatch = Pattern.matches("/index[^\\s]*", path);
    boolean bookMatch = Pattern.matches("/book/[^\\s]*", path);

    // 白名单接口、开放接口放行
    if (bookMatch || indexMatch || whiteList.contains(path)) {
        return chain.filter(exchange);
    }

    String[] segments = path.split("/");
    if (!whiteList.contains(segments[1])) {
        // 认证
        String token = exchange.getRequest().getHeaders().getFirst("token");
        Result<User> result = JwtUtil.validationToken(token);
        if (result.getCode() == HttpCodeEnum.OK.getCode()) {
            // 认证通过
            User user = result.getData();
            // 追加请求头用户信息
            Consumer<HttpHeaders> httpHeaders = httpHeader -> {
                httpHeader.set("userId",user.getId().toString());
                httpHeader.set("nickName",user.getNickName());
            };
            ServerHttpRequest serverHttpRequest = exchange.getRequest()
                    .mutate()
                    .headers(httpHeaders)
                    .build();
            exchange.mutate().request(serverHttpRequest).build();
            return chain.filter(exchange);
        }

        // 认证过期、失败,均返回401
        ServerHttpResponse response = exchange.getResponse();
        byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 指定编码,否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
    return chain.filter(exchange);
}