Java Code Examples for org.springframework.web.server.WebFilterChain#filter()

The following examples show how to use org.springframework.web.server.WebFilterChain#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: GatewayContextFilter.java    From open-cloud with MIT License 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain){
    ServerHttpRequest request = exchange.getRequest();
    GatewayContext gatewayContext = new GatewayContext();
    HttpHeaders headers = request.getHeaders();
    gatewayContext.setRequestHeaders(headers);
    gatewayContext.getAllRequestData().addAll(request.getQueryParams());
    /*
     * save gateway context into exchange
     */
    exchange.getAttributes().put(GatewayContext.CACHE_GATEWAY_CONTEXT,gatewayContext);
    MediaType contentType = headers.getContentType();
    if(headers.getContentLength()>0){
        if(MediaType.APPLICATION_JSON.equals(contentType) || MediaType.APPLICATION_JSON_UTF8.equals(contentType)){
            return readBody(exchange, chain,gatewayContext);
        }
        if(MediaType.APPLICATION_FORM_URLENCODED.equals(contentType)){
            return readFormData(exchange, chain,gatewayContext);
        }
    }
    log.debug("[GatewayContext]ContentType:{},Gateway context is set with {}",contentType, gatewayContext);
    return chain.filter(exchange);

}
 
Example 2
Source File: GatewayApplication.java    From MyShopPlus with Apache License 2.0 6 votes vote down vote up
@Bean
public WebFilter corsFilter() {
    return (ServerWebExchange ctx, WebFilterChain chain) -> {
        ServerHttpRequest request = ctx.getRequest();
        if (!CorsUtils.isCorsRequest(request)) {
            return chain.filter(ctx);
        }
        HttpHeaders requestHeaders = request.getHeaders();
        ServerHttpResponse response = ctx.getResponse();
        HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
        HttpHeaders headers = response.getHeaders();
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
        headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders());
        if (requestMethod != null) {
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
        }
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        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(ctx);
    };
}
 
Example 3
Source File: CorsConfig.java    From microservice-recruit with Apache License 2.0 6 votes vote down vote up
@Bean
public WebFilter corsFilter() {
    return (ServerWebExchange ctx, WebFilterChain chain) -> {
        ServerHttpRequest request = ctx.getRequest();
        if (CorsUtils.isCorsRequest(request)) {
            HttpHeaders requestHeaders = request.getHeaders();
            ServerHttpResponse response = ctx.getResponse();
            HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
            HttpHeaders headers = response.getHeaders();
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
            headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders
                    .getAccessControlRequestHeaders());
            if(requestMethod != null){
                headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
            }
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
            headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
            headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
            if (request.getMethod() == HttpMethod.OPTIONS) {
                response.setStatusCode(HttpStatus.OK);
                return Mono.empty();
            }
        }
        return chain.filter(ctx);
    };
}
 
Example 4
Source File: TracingWebFilter.java    From java-spring-web with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> filter(final ServerWebExchange exchange, final WebFilterChain chain) {
    final ServerHttpRequest request = exchange.getRequest();

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

    if (exchange.getAttribute(SERVER_SPAN_CONTEXT) != null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Not tracing request " + request + " because it is already being traced");
        }
        return chain.filter(exchange);
    }

    return new TracingOperator(chain.filter(exchange), exchange, tracer, spanDecorators);
}
 
Example 5
Source File: CrossFilter.java    From soul with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("all")
public Mono<Void> filter(final ServerWebExchange exchange, final WebFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    if (CorsUtils.isCorsRequest(request)) {
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = response.getHeaders();
        headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN);
        headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS);
        headers.add("Access-Control-Max-Age", MAX_AGE);
        headers.add("Access-Control-Allow-Headers", ALLOWED_HEADERS);
        headers.add("Access-Control-Expose-Headers", ALLOWED_EXPOSE);
        headers.add("Access-Control-Allow-Credentials", "true");
        if (request.getMethod() == HttpMethod.OPTIONS) {
            response.setStatusCode(HttpStatus.OK);
            return Mono.empty();
        }
    }
    return chain.filter(exchange);
}
 
Example 6
Source File: CorsConfig.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
@Bean
public WebFilter corsFilter() {
    return (ServerWebExchange ctx, WebFilterChain chain) -> {
        ServerHttpRequest request = ctx.getRequest();
        if (!CorsUtils.isCorsRequest(request))
            return chain.filter(ctx);
        HttpHeaders requestHeaders = request.getHeaders();
        ServerHttpResponse response = ctx.getResponse();
        HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
        HttpHeaders headers = response.getHeaders();
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
        headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders());
        if (requestMethod != null)
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        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(ctx);
    };
}
 
Example 7
Source File: WebFluxSecurityCorsFilter.java    From FEBS-Cloud with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("all")
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    if (CorsUtils.isCorsRequest(request)) {
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = response.getHeaders();
        headers.add("Access-Control-Allow-Origin", "*");
        headers.add("Access-Control-Allow-Methods", "*");
        headers.add("Access-Control-Max-Age", "3600");
        headers.add("Access-Control-Allow-Headers", "*");
        if (request.getMethod() == HttpMethod.OPTIONS) {
            response.setStatusCode(HttpStatus.OK);
            return Mono.empty();
        }
    }
    return chain.filter(exchange);
}
 
Example 8
Source File: KeystoneAuthWebFilter.java    From alcor with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    String token = exchange.getRequest().getHeaders().getFirst(AUTHORIZE_TOKEN);
    if(token == null){
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
    String projectId = keystoneClient.verifyToken(token);
    if("".equals(projectId)){
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
    // rewrite uri path include project id
    ServerHttpRequest req = exchange.getRequest();
    ServerWebExchangeUtils.addOriginalRequestUrl(exchange, req.getURI());
    String path = req.getURI().getRawPath();
    String newPath = path.replaceAll(neutronUrlPrefix, "/project/" + projectId);
    ServerHttpRequest request = req.mutate().path(newPath).build();
    exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, request.getURI());
    return chain.filter(exchange.mutate().request(request).build());
}
 
Example 9
Source File: CorsConfig.java    From black-shop with Apache License 2.0 5 votes vote down vote up
@Bean
public WebFilter corsFilter() {
	return (ServerWebExchange ctx, WebFilterChain chain) -> {
		ServerHttpRequest request = ctx.getRequest();
		if (CorsUtils.isCorsRequest(request)) {
			HttpHeaders requestHeaders = request.getHeaders();
			ServerHttpResponse response = ctx.getResponse();
			HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
			HttpHeaders headers = response.getHeaders();
			headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
			headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS,
					requestHeaders.getAccessControlRequestHeaders());
			if (requestMethod != null) {
				headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
			}
			headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
			headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
			headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
			if (request.getMethod() == HttpMethod.OPTIONS) {
				response.setStatusCode(HttpStatus.OK);
				return Mono.empty();
			}

		}
		return chain.filter(ctx);
	};
}
 
Example 10
Source File: FileSizeFilter.java    From soul with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Mono<Void> filter(@NonNull final ServerWebExchange exchange, @NonNull final WebFilterChain chain) {
    MediaType mediaType = exchange.getRequest().getHeaders().getContentType();
    if (MediaType.MULTIPART_FORM_DATA.isCompatibleWith(mediaType)) {
        ServerRequest serverRequest = ServerRequest.create(exchange,
                messageReaders);
        return serverRequest.bodyToMono(DataBuffer.class)
                .flatMap(size -> {
                    if (size.capacity() > BYTES_PER_MB * maxSize) {
                        ServerHttpResponse response = exchange.getResponse();
                        response.setStatusCode(HttpStatus.BAD_REQUEST);
                        Object error = SoulResultWarp.error(SoulResultEnum.PAYLOAD_TOO_LARGE.getCode(), SoulResultEnum.PAYLOAD_TOO_LARGE.getMsg(), null);
                        return WebFluxResultUtils.result(exchange, error);
                    }
                    BodyInserter bodyInserter = BodyInserters.fromPublisher(Mono.just(size), DataBuffer.class);
                    HttpHeaders headers = new HttpHeaders();
                    headers.putAll(exchange.getRequest().getHeaders());
                    headers.remove(HttpHeaders.CONTENT_LENGTH);
                    CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(
                            exchange, headers);
                    return bodyInserter.insert(outputMessage, new BodyInserterContext())
                            .then(Mono.defer(() -> {
                                ServerHttpRequest decorator = decorate(exchange, outputMessage);
                                return chain.filter(exchange.mutate().request(decorator).build());

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

}
 
Example 11
Source File: ParameterValidator.java    From staccato with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    MultiValueMap<String, String> requestParams = exchange.getRequest().getQueryParams();
    requestParams.keySet().forEach(key -> {
        if (!apiParameters.contains(key.toLowerCase())) {
            throw new InvalidParameterException(key, apiParameters);
        }
    });

    return chain.filter(exchange);
}
 
Example 12
Source File: MockServerSpecTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
	String name = "test-attribute";
	String value = exchange.getAttributeOrDefault(name, "");
	exchange.getAttributes().put(name, value + ":" + this.name);
	return chain.filter(exchange);
}
 
Example 13
Source File: CorsWebFilter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
	ServerHttpRequest request = exchange.getRequest();
	CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(exchange);
	boolean isValid = this.processor.process(corsConfiguration, exchange);
	if (!isValid || CorsUtils.isPreFlightRequest(request)) {
		return Mono.empty();
	}
	return chain.filter(exchange);
}
 
Example 14
Source File: RouterFunctionsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void toHttpHandlerWebFilter() {
	AtomicBoolean filterInvoked = new AtomicBoolean();

	WebFilter webFilter = new WebFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
			filterInvoked.set(true);
			return chain.filter(exchange);
		}
	};

	HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.accepted().build();
	RouterFunction<ServerResponse> routerFunction =
			RouterFunctions.route(RequestPredicates.all(), handlerFunction);

	HandlerStrategies handlerStrategies = HandlerStrategies.builder()
			.webFilter(webFilter).build();

	HttpHandler result = RouterFunctions.toHttpHandler(routerFunction, handlerStrategies);
	assertNotNull(result);

	MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build();
	MockServerHttpResponse httpResponse = new MockServerHttpResponse();
	result.handle(httpRequest, httpResponse).block();
	assertEquals(HttpStatus.ACCEPTED, httpResponse.getStatusCode());

	assertTrue(filterInvoked.get());
}
 
Example 15
Source File: RequestAuthFilter.java    From demo-spring-webflux-api-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
	    exchange.getAttributes().put(Constant.WEB_FILTER_ATTR_NAME,chain);
	    if(!authRequest(exchange)) {
		   //forward to 验证失败后controller
	    	   return WebfluxForwardingUtil.forward(Constant.AUTH_FAILED_PATH, exchange,null);
    }
    else {
    	   //forward to 反向代理reverse proxy controller
       return chain.filter(exchange);
    }
}
 
Example 16
Source File: ContextPathFilter.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    String contextPath = serverProperties.getServlet().getContextPath();
    String requestPath = exchange.getRequest().getPath().pathWithinApplication().value();
    if (contextPath != null && requestPath.startsWith(contextPath)) {
        requestPath = requestPath.substring(contextPath.length());
    }
    return chain.filter(exchange.mutate().request(exchange.getRequest().mutate().path(requestPath).build()).build());
}
 
Example 17
Source File: RateLimitFilter.java    From demo-spring-webflux-api-gateway with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
	//doRateLimit(exchange, chain);
	return chain.filter(exchange);
}
 
Example 18
Source File: WebfluxWebFilter.java    From bucket4j-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
	ServerHttpRequest request = exchange.getRequest();
	ServerHttpResponse response = exchange.getResponse();
	List<CompletableFuture<Long>> rateLimitFutures = new ArrayList<>();
	
	if (request.getURI().getPath().matches(filterConfig.getUrl())) {
	
        for (RateLimitCheck<ServerHttpRequest> rl : filterConfig.getRateLimitChecks()) {
			ConsumptionProbeHolder probeHolder = rl.rateLimit(request, true);
			if(probeHolder != null && probeHolder.getConsumptionProbeCompletableFuture() != null ) {
				
				CompletableFuture<ConsumptionProbe> limitCheckingFuture = probeHolder.getConsumptionProbeCompletableFuture();
				rateLimitFutures.add(limitCheckingFuture.thenCompose(probe -> {
					if(probe.isConsumed()) {
						return CompletableFuture.completedFuture(probe.getRemainingTokens());
					} else{	
						return CompletableFuture.completedFuture(null);
					}
		        }));
			}
			
		};
		
		CompletableFuture<Long> reduced = rateLimitFutures
			.stream()
			.reduce((CompletableFuture<Long>)null, (a1, b1) -> {
				if(a1 == null){
					return b1;
				}
				if(filterConfig.getStrategy().equals(RateLimitConditionMatchingStrategy.FIRST)) {
					return a1;
				}
				return a1.thenCombine(b1, (x,y) -> {
					if(x == null && y == null) {
						return null;
					}
					if(x != null && y == null) {
						return x;
					}
					if(x == null && y != null) {
						return y;
					}
					return x < y ? x : y;
					});
			});
		
		Long remainingLimit = null;
		if (reduced != null) {
			remainingLimit = reduced.join();
		}
		
		if(remainingLimit == null || remainingLimit < 0) {
        	return Mono.error(new WebfluxRateLimitException(filterConfig.getHttpResponseBody()));
        }
		if(remainingLimit != null) {
			response.getHeaders().set("X-Rate-Limit-Remaining", "" + remainingLimit);
		}
		return chain.filter(exchange);
	}
	return chain.filter(exchange);
}
 
Example 19
Source File: PreCheckFilter.java    From open-cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    ServerHttpResponse response = exchange.getResponse();
    String requestPath = request.getURI().getPath();
    String remoteIpAddress = ReactiveWebUtils.getRemoteAddress(exchange);
    String origin = request.getHeaders().getOrigin();
    AuthorityResource resource = accessManager.getResource(requestPath);
    if (resource != null) {
        if ("0".equals(resource.getIsOpen().toString())) {
            // 未公开
            return accessDeniedHandler.handle(exchange, new AccessDeniedException(ErrorCode.ACCESS_DENIED_NOT_OPEN.getMessage()));
        }
        if ("0".equals(resource.getStatus().toString())) {
            // 禁用
            return accessDeniedHandler.handle(exchange, new AccessDeniedException(ErrorCode.ACCESS_DENIED_DISABLED.getMessage()));
        } else if ("2".equals(resource.getStatus().toString())) {
            // 维护中
            return accessDeniedHandler.handle(exchange, new AccessDeniedException(ErrorCode.ACCESS_DENIED_UPDATING.getMessage()));
        }
    }
    // 1.ip黑名单检测
    boolean deny = accessManager.matchIpOrOriginBlacklist(requestPath, remoteIpAddress,origin);
    if (deny) {
        // 拒绝
        return accessDeniedHandler.handle(exchange, new AccessDeniedException(ErrorCode.ACCESS_DENIED_BLACK_LIMITED.getMessage()));
    }

    // 3.ip白名单检测
    Boolean[] matchIpWhiteListResult = accessManager.matchIpOrOriginWhiteList(requestPath, remoteIpAddress,origin);
    boolean hasWhiteList = matchIpWhiteListResult[0];
    boolean allow = matchIpWhiteListResult[1];
    if (hasWhiteList) {
        // 接口存在白名单限制
        if (!allow) {
            // IP白名单检测通过,拒绝
            return accessDeniedHandler.handle(exchange, new AccessDeniedException(ErrorCode.ACCESS_DENIED_WHITE_LIMITED.getMessage()));
        }
    }
    return chain.filter(exchange);
}
 
Example 20
Source File: ExchangeMutatorTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
	exchange = exchange.mutate().principal(this.userMono).build();
	return chain.filter(exchange);
}