Java Code Examples for org.springframework.web.cors.reactive.CorsUtils

The following examples show how to use org.springframework.web.cors.reactive.CorsUtils. 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: 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 2
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 3
Source Project: spring-analysis-note   Source File: AbstractHandlerMapping.java    License: MIT License 6 votes vote down vote up
@Override
public Mono<Object> getHandler(ServerWebExchange exchange) {
	return getHandlerInternal(exchange).map(handler -> {
		if (logger.isDebugEnabled()) {
			logger.debug(exchange.getLogPrefix() + "Mapped to " + handler);
		}
		if (hasCorsConfigurationSource(handler)) {
			ServerHttpRequest request = exchange.getRequest();
			CorsConfiguration config = (this.corsConfigurationSource != null ? this.corsConfigurationSource.getCorsConfiguration(exchange) : null);
			CorsConfiguration handlerConfig = getCorsConfiguration(handler, exchange);
			config = (config != null ? config.combine(handlerConfig) : handlerConfig);
			if (!this.corsProcessor.process(config, exchange) || CorsUtils.isPreFlightRequest(request)) {
				return REQUEST_HANDLED_HANDLER;
			}
		}
		return handler;
	});
}
 
Example 4
Source Project: spring-analysis-note   Source File: ConsumesRequestCondition.java    License: MIT License 6 votes vote down vote up
/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#includes(MediaType)}.
 * @param exchange the current exchange
 * @return the same instance if the condition contains no expressions;
 * or a new condition with matching expressions only;
 * or {@code null} if no expressions match.
 */
@Override
public ConsumesRequestCondition getMatchingCondition(ServerWebExchange exchange) {
	ServerHttpRequest request = exchange.getRequest();
	if (CorsUtils.isPreFlightRequest(request)) {
		return EMPTY_CONDITION;
	}
	if (isEmpty()) {
		return this;
	}
	if (!hasBody(request) && !this.bodyRequired) {
		return EMPTY_CONDITION;
	}
	List<ConsumeMediaTypeExpression> result = getMatchingExpressions(exchange);
	return !CollectionUtils.isEmpty(result) ? new ConsumesRequestCondition(result) : null;
}
 
Example 5
Source Project: spring-analysis-note   Source File: ProducesRequestCondition.java    License: MIT License 6 votes vote down vote up
/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#isCompatibleWith(MediaType)}.
 * @param exchange the current exchange
 * @return the same instance if there are no expressions;
 * or a new condition with matching expressions;
 * or {@code null} if no expressions match.
 */
@Override
@Nullable
public ProducesRequestCondition getMatchingCondition(ServerWebExchange exchange) {
	if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
		return EMPTY_CONDITION;
	}
	if (isEmpty()) {
		return this;
	}
	List<ProduceMediaTypeExpression> result = getMatchingExpressions(exchange);
	if (!CollectionUtils.isEmpty(result)) {
		return new ProducesRequestCondition(result, this);
	}
	else {
		try {
			if (MediaType.ALL.isPresentIn(getAcceptedMediaTypes(exchange))) {
				return EMPTY_CONDITION;
			}
		}
		catch (NotAcceptableStatusException | UnsupportedMediaTypeStatusException ex) {
			// Ignore
		}
	}
	return null;
}
 
Example 6
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 7
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 8
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 9
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 10
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 11
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 12
Source Project: java-technology-stack   Source File: AbstractHandlerMapping.java    License: MIT License 6 votes vote down vote up
@Override
public Mono<Object> getHandler(ServerWebExchange exchange) {
	return getHandlerInternal(exchange).map(handler -> {
		if (logger.isDebugEnabled()) {
			logger.debug(exchange.getLogPrefix() + "Mapped to " + handler);
		}
		if (CorsUtils.isCorsRequest(exchange.getRequest())) {
			CorsConfiguration configA = this.corsConfigurationSource.getCorsConfiguration(exchange);
			CorsConfiguration configB = getCorsConfiguration(handler, exchange);
			CorsConfiguration config = (configA != null ? configA.combine(configB) : configB);
			if (!getCorsProcessor().process(config, exchange) ||
					CorsUtils.isPreFlightRequest(exchange.getRequest())) {
				return REQUEST_HANDLED_HANDLER;
			}
		}
		return handler;
	});
}
 
Example 13
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 14
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 15
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 16
/**
 * Check if any of the HTTP request methods match the given request and
 * return an instance that contains the matching HTTP request method only.
 * @param exchange the current exchange
 * @return the same instance if the condition is empty (unless the request
 * method is HTTP OPTIONS), a new condition with the matched request method,
 * or {@code null} if there is no match or the condition is empty and the
 * request method is OPTIONS.
 */
@Override
@Nullable
public RequestMethodsRequestCondition getMatchingCondition(ServerWebExchange exchange) {
	if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
		return matchPreFlight(exchange.getRequest());
	}
	if (getMethods().isEmpty()) {
		if (RequestMethod.OPTIONS.name().equals(exchange.getRequest().getMethodValue())) {
			return null; // We handle OPTIONS transparently, so don't match if no explicit declarations
		}
		return this;
	}
	return matchRequestMethod(exchange.getRequest().getMethodValue());
}
 
Example 17
Source Project: spring-analysis-note   Source File: HeadersRequestCondition.java    License: MIT License 5 votes vote down vote up
/**
 * Returns "this" instance if the request matches all expressions;
 * or {@code null} otherwise.
 */
@Override
@Nullable
public HeadersRequestCondition getMatchingCondition(ServerWebExchange exchange) {
	if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
		return PRE_FLIGHT_MATCH;
	}
	for (HeaderExpression expression : this.expressions) {
		if (!expression.match(exchange)) {
			return null;
		}
	}
	return this;
}
 
Example 18
/**
 * Look up the best-matching handler method for the current request.
 * If multiple matches are found, the best match is selected.
 * @param exchange the current exchange
 * @return the best-matching handler method, or {@code null} if no match
 * @see #handleMatch
 * @see #handleNoMatch
 */
@Nullable
protected HandlerMethod lookupHandlerMethod(ServerWebExchange exchange) throws Exception {
	List<Match> matches = new ArrayList<>();
	addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, exchange);

	if (!matches.isEmpty()) {
		Comparator<Match> comparator = new MatchComparator(getMappingComparator(exchange));
		matches.sort(comparator);
		Match bestMatch = matches.get(0);
		if (matches.size() > 1) {
			if (logger.isTraceEnabled()) {
				logger.trace(exchange.getLogPrefix() + matches.size() + " matching mappings: " + matches);
			}
			if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
				return PREFLIGHT_AMBIGUOUS_MATCH;
			}
			Match secondBestMatch = matches.get(1);
			if (comparator.compare(bestMatch, secondBestMatch) == 0) {
				Method m1 = bestMatch.handlerMethod.getMethod();
				Method m2 = secondBestMatch.handlerMethod.getMethod();
				RequestPath path = exchange.getRequest().getPath();
				throw new IllegalStateException(
						"Ambiguous handler methods mapped for '" + path + "': {" + m1 + ", " + m2 + "}");
			}
		}
		handleMatch(bestMatch.mapping, bestMatch.handlerMethod, exchange);
		return bestMatch.handlerMethod;
	}
	else {
		return handleNoMatch(this.mappingRegistry.getMappings().keySet(), exchange);
	}
}
 
Example 19
Source Project: java-technology-stack   Source File: ConsumesRequestCondition.java    License: MIT License 5 votes vote down vote up
/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#includes(MediaType)}.
 * @param exchange the current exchange
 * @return the same instance if the condition contains no expressions;
 * or a new condition with matching expressions only;
 * or {@code null} if no expressions match.
 */
@Override
public ConsumesRequestCondition getMatchingCondition(ServerWebExchange exchange) {
	if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
		return PRE_FLIGHT_MATCH;
	}
	if (isEmpty()) {
		return this;
	}
	Set<ConsumeMediaTypeExpression> result = new LinkedHashSet<>(this.expressions);
	result.removeIf(expression -> !expression.match(exchange));
	return (!result.isEmpty() ? new ConsumesRequestCondition(result) : null);
}
 
Example 20
/**
 * Check if any of the HTTP request methods match the given request and
 * return an instance that contains the matching HTTP request method only.
 * @param exchange the current exchange
 * @return the same instance if the condition is empty (unless the request
 * method is HTTP OPTIONS), a new condition with the matched request method,
 * or {@code null} if there is no match or the condition is empty and the
 * request method is OPTIONS.
 */
@Override
@Nullable
public RequestMethodsRequestCondition getMatchingCondition(ServerWebExchange exchange) {
	if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
		return matchPreFlight(exchange.getRequest());
	}
	if (getMethods().isEmpty()) {
		if (RequestMethod.OPTIONS.name().equals(exchange.getRequest().getMethodValue())) {
			return null; // No implicit match for OPTIONS (we handle it)
		}
		return this;
	}
	return matchRequestMethod(exchange.getRequest().getMethod());
}
 
Example 21
Source Project: java-technology-stack   Source File: HeadersRequestCondition.java    License: MIT License 5 votes vote down vote up
/**
 * Returns "this" instance if the request matches all expressions;
 * or {@code null} otherwise.
 */
@Override
@Nullable
public HeadersRequestCondition getMatchingCondition(ServerWebExchange exchange) {
	if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
		return PRE_FLIGHT_MATCH;
	}
	for (HeaderExpression expression : this.expressions) {
		if (!expression.match(exchange)) {
			return null;
		}
	}
	return this;
}
 
Example 22
Source Project: java-technology-stack   Source File: ProducesRequestCondition.java    License: MIT License 5 votes vote down vote up
/**
 * Checks if any of the contained media type expressions match the given
 * request 'Content-Type' header and returns an instance that is guaranteed
 * to contain matching expressions only. The match is performed via
 * {@link MediaType#isCompatibleWith(MediaType)}.
 * @param exchange the current exchange
 * @return the same instance if there are no expressions;
 * or a new condition with matching expressions;
 * or {@code null} if no expressions match.
 */
@Override
@Nullable
public ProducesRequestCondition getMatchingCondition(ServerWebExchange exchange) {
	if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
		return PRE_FLIGHT_MATCH;
	}
	if (isEmpty()) {
		return this;
	}
	Set<ProduceMediaTypeExpression> result = new LinkedHashSet<>(this.expressions);
	result.removeIf(expression -> !expression.match(exchange));
	if (!result.isEmpty()) {
		return new ProducesRequestCondition(result, this.contentTypeResolver);
	}
	else {
		try {
			if (MediaType.ALL.isPresentIn(getAcceptedMediaTypes(exchange))) {
				return EMPTY_CONDITION;
			}
		}
		catch (NotAcceptableStatusException | UnsupportedMediaTypeStatusException ex) {
			// Ignore
		}
	}
	return null;
}
 
Example 23
/**
 * Look up the best-matching handler method for the current request.
 * If multiple matches are found, the best match is selected.
 * @param exchange the current exchange
 * @return the best-matching handler method, or {@code null} if no match
 * @see #handleMatch
 * @see #handleNoMatch
 */
@Nullable
protected HandlerMethod lookupHandlerMethod(ServerWebExchange exchange) throws Exception {
	List<Match> matches = new ArrayList<>();
	addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, exchange);

	if (!matches.isEmpty()) {
		Comparator<Match> comparator = new MatchComparator(getMappingComparator(exchange));
		matches.sort(comparator);
		Match bestMatch = matches.get(0);
		if (matches.size() > 1) {
			if (logger.isTraceEnabled()) {
				logger.trace(exchange.getLogPrefix() + matches.size() + " matching mappings: " + matches);
			}
			if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
				return PREFLIGHT_AMBIGUOUS_MATCH;
			}
			Match secondBestMatch = matches.get(1);
			if (comparator.compare(bestMatch, secondBestMatch) == 0) {
				Method m1 = bestMatch.handlerMethod.getMethod();
				Method m2 = secondBestMatch.handlerMethod.getMethod();
				RequestPath path = exchange.getRequest().getPath();
				throw new IllegalStateException(
						"Ambiguous handler methods mapped for '" + path + "': {" + m1 + ", " + m2 + "}");
			}
		}
		handleMatch(bestMatch.mapping, bestMatch.handlerMethod, exchange);
		return bestMatch.handlerMethod;
	}
	else {
		return handleNoMatch(this.mappingRegistry.getMappings().keySet(), exchange);
	}
}
 
Example 24
Source Project: black-shop   Source File: CorsConfig.java    License: 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 25
Source Project: zuihou-admin-cloud   Source File: CorsConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * attention:简单跨域就是GET,HEAD和POST请求,但是POST请求的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain
 * 反之,就是非简单跨域,此跨域有一个预检机制,说直白点,就是会发两次请求,一次OPTIONS请求,一次真正的请求
 */
@Bean
public WebFilter corsFilter() {
    return (ctx, 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);
    };
}