Java Code Examples for org.springframework.web.server.WebFilterChain

The following examples show how to use org.springframework.web.server.WebFilterChain. 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: light-security   Source File: AuthWebFilter.java    License: Apache License 2.0 7 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();

    Mono<Boolean> mono = specList.stream()
            .filter(spec -> ReactiveRestfulMatchUtil.match(request, spec.getHttpMethod(), spec.getPath()))
            .findFirst()
            .map(spec -> {
                String expression = spec.getExpression();
                return ReactiveSpringElCheckUtil.check(
                        new StandardEvaluationContext(reactivePreAuthorizeExpressionRoot),
                        expression
                );

            })
            .orElse(Mono.just(true));

    return mono.filter(t -> t)
            .switchIfEmpty(Mono.error(new LightSecurityException("Access Denied")))
            .flatMap(t -> chain.filter(exchange));
}
 
Example 2
Source Project: microservice-recruit   Source File: CorsConfig.java    License: 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 3
Source Project: MyShopPlus   Source File: GatewayApplication.java    License: 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 4
Source Project: spring-analysis-note   Source File: CorsWebFilterTests.java    License: MIT License 6 votes vote down vote up
@Test
public void nonCorsRequest() {
	WebFilterChain filterChain = filterExchange -> {
		try {
			HttpHeaders headers = filterExchange.getResponse().getHeaders();
			assertNull(headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
			assertNull(headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS));
		}
		catch (AssertionError ex) {
			return Mono.error(ex);
		}
		return Mono.empty();

	};
	MockServerWebExchange exchange = MockServerWebExchange.from(
			MockServerHttpRequest
					.get("https://domain1.com/test.html")
					.header(HOST, "domain1.com"));
	this.filter.filter(exchange, filterChain).block();
}
 
Example 5
Source Project: spring-analysis-note   Source File: CorsWebFilterTests.java    License: MIT License 6 votes vote down vote up
@Test
public void sameOriginRequest() {
	WebFilterChain filterChain = filterExchange -> {
		try {
			HttpHeaders headers = filterExchange.getResponse().getHeaders();
			assertNull(headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
			assertNull(headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS));
		}
		catch (AssertionError ex) {
			return Mono.error(ex);
		}
		return Mono.empty();

	};
	MockServerWebExchange exchange = MockServerWebExchange.from(
			MockServerHttpRequest
					.get("https://domain1.com/test.html")
					.header(ORIGIN, "https://domain1.com"));
	this.filter.filter(exchange, filterChain).block();
}
 
Example 6
Source Project: spring-analysis-note   Source File: CorsWebFilterTests.java    License: MIT License 6 votes vote down vote up
@Test
public void validActualRequest() {
	WebFilterChain filterChain = filterExchange -> {
		try {
			HttpHeaders headers = filterExchange.getResponse().getHeaders();
			assertEquals("https://domain2.com", headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
			assertEquals("header3, header4", headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS));
		}
		catch (AssertionError ex) {
			return Mono.error(ex);
		}
		return Mono.empty();

	};
	MockServerWebExchange exchange = MockServerWebExchange.from(
			MockServerHttpRequest
					.get("https://domain1.com/test.html")
					.header(HOST, "domain1.com")
					.header(ORIGIN, "https://domain2.com")
					.header("header2", "foo"));
	this.filter.filter(exchange, filterChain).block();
}
 
Example 7
Source Project: spring-analysis-note   Source File: CorsWebFilterTests.java    License: MIT License 6 votes vote down vote up
@Test
public void validPreFlightRequest() throws ServletException, IOException {

	MockServerWebExchange exchange = MockServerWebExchange.from(
			MockServerHttpRequest
					.options("https://domain1.com/test.html")
					.header(HOST, "domain1.com")
					.header(ORIGIN, "https://domain2.com")
					.header(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.GET.name())
					.header(ACCESS_CONTROL_REQUEST_HEADERS, "header1, header2")
	);

	WebFilterChain filterChain = filterExchange -> Mono.error(
			new AssertionError("Preflight requests must not be forwarded to the filter chain"));
	filter.filter(exchange, filterChain).block();

	HttpHeaders headers = exchange.getResponse().getHeaders();
	assertEquals("https://domain2.com", headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertEquals("header1, header2", headers.getFirst(ACCESS_CONTROL_ALLOW_HEADERS));
	assertEquals("header3, header4", headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS));
	assertEquals(123L, Long.parseLong(headers.getFirst(ACCESS_CONTROL_MAX_AGE)));
}
 
Example 8
Source Project: spring-analysis-note   Source File: CorsWebFilterTests.java    License: MIT License 6 votes vote down vote up
@Test
public void invalidPreFlightRequest() throws ServletException, IOException {

	MockServerWebExchange exchange = MockServerWebExchange.from(
			MockServerHttpRequest
					.options("https://domain1.com/test.html")
					.header(HOST, "domain1.com")
					.header(ORIGIN, "https://domain2.com")
					.header(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.DELETE.name())
					.header(ACCESS_CONTROL_REQUEST_HEADERS, "header1, header2"));

	WebFilterChain filterChain = filterExchange -> Mono.error(
			new AssertionError("Preflight requests must not be forwarded to the filter chain"));

	filter.filter(exchange, filterChain).block();

	assertNull(exchange.getResponse().getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
}
 
Example 9
Source Project: open-capacity-platform   Source File: CorsConfig.java    License: 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 10
Source Project: FEBS-Cloud   Source File: WebFluxSecurityCorsFilter.java    License: 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 11
Source Project: spring-microservice-exam   Source File: CorsConfig.java    License: 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 12
Source Project: simple-microservice   Source File: CorsConfig.java    License: 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 13
Source Project: open-cloud   Source File: ResourceServerConfiguration.java    License: MIT License 6 votes vote down vote up
/**
 * 跨域配置
 *
 * @return
 */
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 14
Source Project: open-cloud   Source File: AccessLogFilter.java    License: MIT License 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    ServerHttpResponse response = exchange.getResponse();
    DataBufferFactory bufferFactory = response.bufferFactory();
    ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(response) {
        @Override
        public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
            if (body instanceof Flux) {
                Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                return super.writeWith(fluxBody.map(dataBuffer -> {
                    // probably should reuse buffers
                    byte[] content = new byte[dataBuffer.readableByteCount()];
                    dataBuffer.read(content);
                    //释放掉内存
                    DataBufferUtils.release(dataBuffer);
                    return bufferFactory.wrap(content);
                }));
            }
            // if body is not a flux. never got there.
            return super.writeWith(body);
        }
    };
    return chain.filter(exchange.mutate().response(decoratedResponse).build()).then(Mono.fromRunnable(()->{
        accessLogService.sendLog(exchange, null);
    }));
}
 
Example 15
Source Project: open-cloud   Source File: GatewayContextFilter.java    License: 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 16
Source Project: spring-cloud-sofastack-samples   Source File: CorsConfig.java    License: 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)) {
            ServerHttpResponse response = ctx.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-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(ctx);
    };
}
 
Example 17
Source Project: alcor   Source File: KeystoneAuthWebFilter.java    License: 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 18
Source Project: microservice-integration   Source File: GatewayConfiguration.java    License: 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)) {
            ServerHttpResponse response = ctx.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);
            if (request.getMethod() == HttpMethod.OPTIONS) {
                response.setStatusCode(HttpStatus.OK);
                return Mono.empty();
            }
        }
        return chain.filter(ctx);
    };
}
 
Example 19
Source Project: java-technology-stack   Source File: CorsWebFilterTests.java    License: MIT License 6 votes vote down vote up
@Test
public void validActualRequest() {
	WebFilterChain filterChain = (filterExchange) -> {
		try {
			HttpHeaders headers = filterExchange.getResponse().getHeaders();
			assertEquals("http://domain2.com", headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
			assertEquals("header3, header4", headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS));
		} catch (AssertionError ex) {
			return Mono.error(ex);
		}
		return Mono.empty();

	};
	MockServerWebExchange exchange = MockServerWebExchange.from(
			MockServerHttpRequest
					.get("http://domain1.com/test.html")
					.header(HOST, "domain1.com")
					.header(ORIGIN, "http://domain2.com")
					.header("header2", "foo"));
	this.filter.filter(exchange, filterChain);
}
 
Example 20
Source Project: java-technology-stack   Source File: CorsWebFilterTests.java    License: MIT License 6 votes vote down vote up
@Test
public void validPreFlightRequest() throws ServletException, IOException {

	MockServerWebExchange exchange = MockServerWebExchange.from(
			MockServerHttpRequest
					.options("http://domain1.com/test.html")
					.header(HOST, "domain1.com")
					.header(ORIGIN, "http://domain2.com")
					.header(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.GET.name())
					.header(ACCESS_CONTROL_REQUEST_HEADERS, "header1, header2")
	);

	WebFilterChain filterChain = (filterExchange) -> Mono.error(
			new AssertionError("Preflight requests must not be forwarded to the filter chain"));
	filter.filter(exchange, filterChain);

	HttpHeaders headers = exchange.getResponse().getHeaders();
	assertEquals("http://domain2.com", headers.getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertEquals("header1, header2", headers.getFirst(ACCESS_CONTROL_ALLOW_HEADERS));
	assertEquals("header3, header4", headers.getFirst(ACCESS_CONTROL_EXPOSE_HEADERS));
	assertEquals(123L, Long.parseLong(headers.getFirst(ACCESS_CONTROL_MAX_AGE)));
}
 
Example 21
Source Project: java-technology-stack   Source File: CorsWebFilterTests.java    License: MIT License 6 votes vote down vote up
@Test
public void invalidPreFlightRequest() throws ServletException, IOException {

	MockServerWebExchange exchange = MockServerWebExchange.from(
			MockServerHttpRequest
					.options("http://domain1.com/test.html")
					.header(HOST, "domain1.com")
					.header(ORIGIN, "http://domain2.com")
					.header(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.DELETE.name())
					.header(ACCESS_CONTROL_REQUEST_HEADERS, "header1, header2"));

	WebFilterChain filterChain = (filterExchange) -> Mono.error(
			new AssertionError("Preflight requests must not be forwarded to the filter chain"));

	filter.filter(exchange, filterChain);

	assertNull(exchange.getResponse().getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
}
 
Example 22
Source Project: soul   Source File: CrossFilter.java    License: 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 23
Source Project: microservice-recruit   Source File: CorsConfig.java    License: 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 24
Source Project: java-specialagent   Source File: TracingWebFilter.java    License: 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 25
Source Project: java-spring-web   Source File: TracingWebFilter.java    License: 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 26
@Before
  public void setup() throws URISyntaxException {
  	rateLimitCheck1 = mock(RateLimitCheck.class);
      rateLimitCheck2 = mock(RateLimitCheck.class);
      rateLimitCheck3 = mock(RateLimitCheck.class);

      exchange = Mockito.mock(ServerWebExchange.class);
      
      ServerHttpRequest serverHttpRequest = Mockito.mock(ServerHttpRequest.class);
      URI uri = new URI("url");
      when(serverHttpRequest.getURI()).thenReturn(uri);
when(exchange.getRequest()).thenReturn(serverHttpRequest);

serverHttpResponse = Mockito.mock(ServerHttpResponse.class);
      when(exchange.getResponse()).thenReturn(serverHttpResponse);
      
chain = Mockito.mock(WebFilterChain.class);
      
      configuration = new FilterConfiguration();
      configuration.setRateLimitChecks(Arrays.asList(rateLimitCheck1, rateLimitCheck2, rateLimitCheck3));
      configuration.setUrl("url");
      filter = new WebfluxWebFilter(configuration);
  }
 
Example 27
@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
    return new HiddenHttpMethodFilter() {
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
            return chain.filter(exchange);
        }
    };
}
 
Example 28
Source Project: spring-analysis-note   Source File: RouterFunctionsTests.java    License: 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 29
Source Project: spring-analysis-note   Source File: CorsWebFilter.java    License: 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 30
Source Project: spring-analysis-note   Source File: HiddenHttpMethodFilter.java    License: MIT License 5 votes vote down vote up
/**
 * Transform an HTTP POST into another method based on {@code methodParamName}.
 * @param exchange the current server exchange
 * @param chain provides a way to delegate to the next filter
 * @return {@code Mono<Void>} to indicate when request processing is complete
 */
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

	if (exchange.getRequest().getMethod() != HttpMethod.POST) {
		return chain.filter(exchange);
	}

	return exchange.getFormData()
			.map(formData -> {
				String method = formData.getFirst(this.methodParamName);
				return StringUtils.hasLength(method) ? mapExchange(exchange, method) : exchange;
			})
			.flatMap(chain::filter);
}