Java Code Examples for org.springframework.http.server.reactive.ServerHttpRequest#Builder

The following examples show how to use org.springframework.http.server.reactive.ServerHttpRequest#Builder . 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: FallbackHeadersGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private ServerWebExchange addFallbackHeaders(Config config,
		ServerWebExchange exchange, Throwable executionException) {
	ServerHttpRequest.Builder requestBuilder = exchange.getRequest().mutate();
	requestBuilder.header(config.executionExceptionTypeHeaderName,
			executionException.getClass().getName());
	requestBuilder.header(config.executionExceptionMessageHeaderName,
			executionException.getMessage());
	Throwable rootCause = getRootCause(executionException);
	if (rootCause != null) {
		requestBuilder.header(config.rootCauseExceptionTypeHeaderName,
				rootCause.getClass().getName());
		requestBuilder.header(config.rootCauseExceptionMessageHeaderName,
				rootCause.getMessage());
	}
	return exchange.mutate().request(requestBuilder.build()).build();
}
 
Example 2
Source File: AccessGatewayFilter.java    From SpringCloud with Apache License 2.0 6 votes vote down vote up
/**
 * 1.首先网关检查token是否有效,无效直接返回401,不调用签权服务
 * 2.调用签权服务器看是否对该请求有权限,有权限进入下一个filter,没有权限返回401
 *
 * @param exchange
 * @param chain
 * @return
 */
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    String authentication = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
    String method = request.getMethodValue();
    String url = request.getPath().value();
    log.debug("url:{},method:{},headers:{}", url, method, request.getHeaders());
    //不需要网关签权的url
    if (authService.ignoreAuthentication(url)) {
        return chain.filter(exchange);
    }

    //调用签权服务看用户是否有权限,若有权限进入下一个filter
    if (permissionService.permission(authentication, url, method)) {
        ServerHttpRequest.Builder builder = request.mutate();
        //TODO 转发的请求都加上服务间认证token
        builder.header(X_CLIENT_TOKEN, "TODO zhoutaoo添加服务间简单认证");
        //将jwt token中的用户信息传给服务
        builder.header(X_CLIENT_TOKEN_USER, getUserToken(authentication));
        return chain.filter(exchange.mutate().request(builder.build()).build());
    }
    return unauthorized(exchange);
}
 
Example 3
Source File: ForwardedHeaderTransformer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Apply and remove, or remove Forwarded type headers.
 * @param request the request
 */
@Override
public ServerHttpRequest apply(ServerHttpRequest request) {
	if (hasForwardedHeaders(request)) {
		ServerHttpRequest.Builder builder = request.mutate();
		if (!this.removeOnly) {
			URI uri = UriComponentsBuilder.fromHttpRequest(request).build(true).toUri();
			builder.uri(uri);
			String prefix = getForwardedPrefix(request);
			if (prefix != null) {
				builder.path(prefix + uri.getPath());
				builder.contextPath(prefix);
			}
		}
		removeForwardedHeaders(builder);
		request = builder.build();
	}
	return request;
}
 
Example 4
Source File: HttpsToHttpFilter.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    URI originalUri = exchange.getRequest().getURI();
    ServerHttpRequest request = exchange.getRequest();
    ServerHttpRequest.Builder mutate = request.mutate();
    String forwardedUri = request.getURI().toString();
    if (forwardedUri != null && forwardedUri.startsWith("https")) {
        try {
            URI mutatedUri = new URI("http",
                    originalUri.getUserInfo(),
                    originalUri.getHost(),
                    originalUri.getPort(),
                    originalUri.getPath(),
                    originalUri.getQuery(),
                    originalUri.getFragment());
            mutate.uri(mutatedUri);
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage(), e);
        }
    }
    ServerHttpRequest build = mutate.build();
    return chain.filter(exchange.mutate().request(build).build());
}
 
Example 5
Source File: TraceRequestHttpHeadersFilter.java    From java-spring-cloud with Apache License 2.0 6 votes vote down vote up
@Override
public HttpHeaders filter(HttpHeaders input, ServerWebExchange exchange) {
  log.debug("Will instrument spring cloud gateway the HTTP request headers");
  ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
  Span span = this.tracer.buildSpan(path(builder))
      .asChildOf(tracer.activeSpan())
      .withTag(Tags.COMPONENT.getKey(), COMPONENT)
      .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
      .withTag(ROUTE_ID, getRouteId(exchange))
      .start();
  log.debug("Client span {} created for the request. New headers are {}", span, builder.build().getHeaders().toSingleValueMap());
  exchange.getAttributes().put(SPAN_ATTRIBUTE, span);
  HttpHeaders headersWithInput = new HttpHeaders();
  try {
    this.tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, new HttpHeadersCarrier(headersWithInput));
  } catch (Exception ignore) {
    log.error("TraceRequestHttpHeadersFilter error", ignore);
  }
  headersWithInput.addAll(input);
  addHeadersWithInput(builder, headersWithInput);
  return headersWithInput;
}
 
Example 6
Source File: ForwardedHeaderTransformer.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Apply and remove, or remove Forwarded type headers.
 * @param request the request
 */
@Override
public ServerHttpRequest apply(ServerHttpRequest request) {
	if (hasForwardedHeaders(request)) {
		ServerHttpRequest.Builder builder = request.mutate();
		if (!this.removeOnly) {
			URI uri = UriComponentsBuilder.fromHttpRequest(request).build(true).toUri();
			builder.uri(uri);
			String prefix = getForwardedPrefix(request);
			if (prefix != null) {
				builder.path(prefix + uri.getPath());
				builder.contextPath(prefix);
			}
		}
		removeForwardedHeaders(builder);
		request = builder.build();
	}
	return request;
}
 
Example 7
Source File: AccessGatewayFilter.java    From JetfireCloud with Apache License 2.0 6 votes vote down vote up
/**
 * 1.首先网关检查token是否有效,无效直接返回401,不调用签权服务
 * 2.调用签权服务器看是否对该请求有权限,有权限进入下一个filter,没有权限返回401
 *
 * @param exchange
 * @param chain
 * @return
 */
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    String authentication = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
    String method = request.getMethodValue();
    String url = request.getPath().value();
    log.debug("url:{},method:{},headers:{}", url, method, request.getHeaders());
    //不需要网关签权的url
    if (authService.ignoreAuthentication(url)) {
        return chain.filter(exchange);
    }
    //调用签权服务看用户是否有权限,若有权限进入下一个filter
    if (authService.hasPermission(authentication, url, method)) {
        ServerHttpRequest.Builder builder = request.mutate();
        //TODO 转发的请求都加上服务间认证token
        builder.header(X_CLIENT_TOKEN, "TODO zhoutaoo添加服务间简单认证");
        //将jwt token中的用户信息传给服务
        builder.header(X_CLIENT_TOKEN_USER, authService.getJwt(authentication).getClaims());
        return chain.filter(exchange.mutate().request(builder.build()).build());
    }
    return unauthorized(exchange);
}
 
Example 8
Source File: TraceRequestHttpHeadersFilter.java    From java-spring-cloud with Apache License 2.0 5 votes vote down vote up
private void addHeadersWithInput(ServerHttpRequest.Builder builder,
                                 HttpHeaders headersWithInput) {
  for (Map.Entry<String, List<String>> entry : builder.build().getHeaders()
      .entrySet()) {
    String key = entry.getKey();
    List<String> value = entry.getValue();
    headersWithInput.put(key, value);
  }
}
 
Example 9
Source File: TokenFilter.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获取token字段,如果能获取到就 pass,获取不到就直接返回401错误,
 * chain.filter(exchange)之前的就是 “pre” 部分,之后的也就是then里边的是 “post” 部分
 * @param exchange
 * @param chain
 * @return
 */
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

	ServerHttpRequest request = exchange.getRequest();
	String authentication = request.getHeaders().getFirst("AUTH");
	String method = request.getMethodValue();
	String url = request.getPath().value();
	LogBack.info("url:{},method:{},headers:{}", url, method, request.getHeaders());
	//不需要网关签权的url
	if (authService.ignoreAuthentication(url) || StringUtils.startsWith(url, "/api")) {
		return chain.filter(exchange);
	}
	// 如果请求未携带token信息, 直接跳出
	if (StringUtils.isBlank(authentication) || !authentication.contains(BEARER)) {
		LogBack.error("url:{},method:{},headers:{}, 请求未携带token信息", url, method, request.getHeaders());
		return unAuthorized(exchange, StatusEnum.PARAM_ILLEGAL);
	}

	long expire = authService.getExpire(authentication);
	// 过期
	if(expire<0){
		return unAuthorized(exchange,StatusEnum.LOGIN_EXPIRED);
	}

	AuthToken authToken = authService.getAuthToken(authentication);
	String jwtToken = authToken.getAccess_token();
	//调用签权服务看用户是否有权限,若有权限进入下一个filter
	if (authService.commonAuthentication(url) || authService.hasPermission(jwtToken, url, method) ) {
		ServerHttpRequest.Builder builder = request.mutate();
		builder.header(X_CLIENT_TOKEN, "TODO 添加服务间简单认证");//TODO 转发的请求都加上服务间认证token
		//将jwt token中的用户信息传给服务
		builder.header(X_CLIENT_TOKEN_USER, authService.getJwt(jwtToken).getClaims());
		builder.header(HttpHeaders.AUTHORIZATION,BEARER+jwtToken);
		return chain.filter(exchange.mutate().request(builder.build()).build());
	}
	return unAuthorized(exchange,StatusEnum.UN_AUTHORIZED);
}
 
Example 10
Source File: TokenFilter.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获取token字段,如果能获取到就 pass,获取不到就直接返回401错误,
 * chain.filter(exchange)之前的就是 “pre” 部分,之后的也就是then里边的是 “post” 部分
 * @param exchange
 * @param chain
 * @return
 */
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

	ServerHttpRequest request = exchange.getRequest();
	String authentication = request.getHeaders().getFirst("AUTH");
	String method = request.getMethodValue();
	String url = request.getPath().value();
	LogBack.info("url:{},method:{},headers:{}", url, method, request.getHeaders());
	//不需要网关签权的url
	if (authService.ignoreAuthentication(url) || StringUtils.startsWith(url, "/api")) {
		return chain.filter(exchange);
	}
	// 如果请求未携带token信息, 直接跳出
	if (StringUtils.isBlank(authentication) || !authentication.contains(BEARER)) {
		LogBack.error("url:{},method:{},headers:{}, 请求未携带token信息", url, method, request.getHeaders());
		return unAuthorized(exchange, StatusEnum.PARAM_ILLEGAL);
	}

	long expire = authService.getExpire(authentication);
	// 过期
	if(expire<0){
		return unAuthorized(exchange,StatusEnum.LOGIN_EXPIRED);
	}

	AuthToken authToken = authService.getAuthToken(authentication);
	String jwtToken = authToken.getAccess_token();
	//调用签权服务看用户是否有权限,若有权限进入下一个filter
	if (authService.commonAuthentication(url) || authService.hasPermission(jwtToken, url, method) ) {
		ServerHttpRequest.Builder builder = request.mutate();
		builder.header(X_CLIENT_TOKEN, "TODO 添加服务间简单认证");//TODO 转发的请求都加上服务间认证token
		//将jwt token中的用户信息传给服务
		builder.header(X_CLIENT_TOKEN_USER, authService.getJwt(jwtToken).getClaims());
		builder.header(HttpHeaders.AUTHORIZATION,BEARER+jwtToken);
		return chain.filter(exchange.mutate().request(builder.build()).build());
	}
	return unAuthorized(exchange,StatusEnum.UN_AUTHORIZED);
}
 
Example 11
Source File: AccessFilter.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
    if (ObjectUtil.isEmpty(value)) {
        return;
    }
    String valueStr = value.toString();
    String valueEncode = URLUtil.encode(valueStr);
    mutate.header(name, valueEncode);
}
 
Example 12
Source File: ForwardedHeaderTransformer.java    From java-technology-stack with MIT License 4 votes vote down vote up
private void removeForwardedHeaders(ServerHttpRequest.Builder builder) {
	builder.headers(map -> FORWARDED_HEADER_NAMES.forEach(map::remove));
}
 
Example 13
Source File: AbstractHttpHeadersFilter.java    From java-spring-cloud with Apache License 2.0 4 votes vote down vote up
public String path(ServerHttpRequest.Builder request) {
  return request.build().getPath().value();
}
 
Example 14
Source File: DefaultServerWebExchangeBuilder.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public ServerWebExchange.Builder request(Consumer<ServerHttpRequest.Builder> consumer) {
	ServerHttpRequest.Builder builder = this.delegate.getRequest().mutate();
	consumer.accept(builder);
	return request(builder.build());
}
 
Example 15
Source File: ForwardedHeaderTransformer.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private void removeForwardedHeaders(ServerHttpRequest.Builder builder) {
	builder.headers(map -> FORWARDED_HEADER_NAMES.forEach(map::remove));
}
 
Example 16
Source File: DefaultServerWebExchangeBuilder.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public ServerWebExchange.Builder request(Consumer<ServerHttpRequest.Builder> consumer) {
	ServerHttpRequest.Builder builder = this.delegate.getRequest().mutate();
	consumer.accept(builder);
	return request(builder.build());
}
 
Example 17
Source File: ServerWebExchange.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Configure a consumer to modify the current request using a builder.
 * <p>Effectively this:
 * <pre>
 * exchange.mutate().request(builder-> builder.method(HttpMethod.PUT));
 *
 * // vs...
 *
 * ServerHttpRequest request = exchange.getRequest().mutate()
 *     .method(HttpMethod.PUT)
 *     .build();
 *
 * exchange.mutate().request(request);
 * </pre>
 * @see ServerHttpRequest#mutate()
 */
Builder request(Consumer<ServerHttpRequest.Builder> requestBuilderConsumer);
 
Example 18
Source File: ServerWebExchange.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Configure a consumer to modify the current request using a builder.
 * <p>Effectively this:
 * <pre>
 * exchange.mutate().request(builder-> builder.method(HttpMethod.PUT));
 *
 * // vs...
 *
 * ServerHttpRequest request = exchange.getRequest().mutate()
 *     .method(HttpMethod.PUT)
 *     .build();
 *
 * exchange.mutate().request(request);
 * </pre>
 * @see ServerHttpRequest#mutate()
 */
Builder request(Consumer<ServerHttpRequest.Builder> requestBuilderConsumer);