Java Code Examples for org.springframework.web.server.ServerWebExchange#getResponse()

The following examples show how to use org.springframework.web.server.ServerWebExchange#getResponse() . 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: ServerWebExchangeUtils.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
public static boolean setResponseStatus(ServerWebExchange exchange,
		HttpStatusHolder statusHolder) {
	if (exchange.getResponse().isCommitted()) {
		return false;
	}
	if (log.isDebugEnabled()) {
		log.debug("Setting response status to " + statusHolder);
	}
	if (statusHolder.getHttpStatus() != null) {
		return setResponseStatus(exchange, statusHolder.getHttpStatus());
	}
	if (statusHolder.getStatus() != null
			&& exchange.getResponse() instanceof AbstractServerHttpResponse) { // non-standard
		((AbstractServerHttpResponse) exchange.getResponse())
				.setStatusCodeValue(statusHolder.getStatus());
		return true;
	}
	return false;
}
 
Example 2
Source File: CorsConfig.java    From simple-microservice 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 3
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 4
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 5
Source File: HttpBinCompatibleController.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@RequestMapping(path = "/gzip", produces = MediaType.APPLICATION_JSON_VALUE)
public Mono<Void> gzip(ServerWebExchange exchange) throws IOException {
	if (log.isDebugEnabled()) {
		log.debug("httpbin /gzip");
	}

	String jsonResponse = OBJECT_MAPPER.writeValueAsString("httpbin compatible home");
	byte[] bytes = jsonResponse.getBytes(StandardCharsets.UTF_8);

	ServerHttpResponse response = exchange.getResponse();
	response.getHeaders().add(HttpHeaders.CONTENT_ENCODING, "gzip");
	DataBufferFactory dataBufferFactory = response.bufferFactory();
	response.setStatusCode(HttpStatus.OK);

	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	GZIPOutputStream is = new GZIPOutputStream(bos);
	FileCopyUtils.copy(bytes, is);

	byte[] gzippedResponse = bos.toByteArray();
	DataBuffer wrap = dataBufferFactory.wrap(gzippedResponse);
	return response.writeWith(Flux.just(wrap));
}
 
Example 6
Source File: TraceRequestHttpHeadersFilter.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Override
public HttpHeaders filter(HttpHeaders input, ServerWebExchange exchange) {
	Object storedSpan = exchange.getAttribute(SPAN_ATTRIBUTE);
	if (storedSpan == null) {
		return input;
	}
	if (log.isDebugEnabled()) {
		log.debug("Will instrument the response");
	}
	HttpClientResponse response = new HttpClientResponse(exchange.getResponse());
	this.handler.handleReceive(response, null, (Span) storedSpan);
	if (log.isDebugEnabled()) {
		log.debug("The response was handled for span " + storedSpan);
	}
	return new HttpHeaders(input);
}
 
Example 7
Source File: DefaultCorsProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void preflightRequestAllowsAllHeaders() throws Exception {
	ServerWebExchange exchange = MockServerWebExchange.from(preFlightRequest()
			.header(ACCESS_CONTROL_REQUEST_METHOD, "GET")
			.header(ACCESS_CONTROL_REQUEST_HEADERS, "Header1, Header2"));

	this.conf.addAllowedHeader("*");
	this.conf.addAllowedOrigin("http://domain2.com");

	this.processor.process(this.conf, exchange);

	ServerHttpResponse response = exchange.getResponse();
	assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS));
	assertTrue(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1"));
	assertTrue(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2"));
	assertFalse(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("*"));
	assertThat(response.getHeaders().get(VARY), contains(ORIGIN,
			ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS));
	assertNull(response.getStatusCode());
}
 
Example 8
Source File: DefaultCorsProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void preflightRequestCredentials() throws Exception {
	ServerWebExchange exchange = MockServerWebExchange.from(preFlightRequest()
			.header(ACCESS_CONTROL_REQUEST_METHOD, "GET")
			.header(ACCESS_CONTROL_REQUEST_HEADERS, "Header1"));

	this.conf.addAllowedOrigin("https://domain1.com");
	this.conf.addAllowedOrigin("https://domain2.com");
	this.conf.addAllowedOrigin("http://domain3.com");
	this.conf.addAllowedHeader("Header1");
	this.conf.setAllowCredentials(true);

	this.processor.process(this.conf, exchange);

	ServerHttpResponse response = exchange.getResponse();
	assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertEquals("https://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
	assertEquals("true", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
	assertThat(response.getHeaders().get(VARY), contains(ORIGIN,
			ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS));
	assertNull(response.getStatusCode());
}
 
Example 9
Source File: DefaultCorsProcessorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void preflightRequestTestWithOriginButWithoutOtherHeaders() throws Exception {
	ServerWebExchange exchange = MockServerWebExchange.from(preFlightRequest());
	this.processor.process(this.conf, exchange);

	ServerHttpResponse response = exchange.getResponse();
	assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertThat(response.getHeaders().get(VARY), contains(ORIGIN,
			ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS));
	assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
}
 
Example 10
Source File: AuthFilter.java    From hello-spring-cloud-alibaba with MIT License 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    String token = exchange.getRequest().getQueryParams().getFirst("token");

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

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

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

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

    return chain.filter(exchange);
}
 
Example 11
Source File: HttpStatusCodeSpanDecorator.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Override
public void onResponse(
        final ServerWebExchange exchange,
        final Span span) {

    final ServerHttpResponse response = exchange.getResponse();
    Optional.ofNullable(response.getStatusCode()).ifPresent(status ->
            span.setTag(HTTP_STATUS, status.value()));
}
 
Example 12
Source File: WebfluxResponseUtil.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
public static Mono<Void> responseWrite(ServerWebExchange exchange, int httpStatus, Result result) {
    if (httpStatus == 0) {
        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value();
    }
    ServerHttpResponse response = exchange.getResponse();
    response.getHeaders().setAccessControlAllowCredentials(true);
    response.getHeaders().setAccessControlAllowOrigin("*");
    response.setStatusCode(HttpStatus.valueOf(httpStatus));
    response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
    DataBufferFactory dataBufferFactory = response.bufferFactory();
    DataBuffer buffer = dataBufferFactory.wrap(JSONObject.toJSONString(result).getBytes(Charset.defaultCharset()));
    return response.writeWith(Mono.just(buffer)).doOnError((error) -> {
        DataBufferUtils.release(buffer);
    });
}
 
Example 13
Source File: DefaultCorsProcessorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void preflightRequestWithRequestAndMethodHeaderButNoConfig() throws Exception {
	ServerWebExchange exchange = MockServerWebExchange.from(preFlightRequest()
			.header(ACCESS_CONTROL_REQUEST_METHOD, "GET")
			.header(ACCESS_CONTROL_REQUEST_HEADERS, "Header1"));

	this.processor.process(this.conf, exchange);

	ServerHttpResponse response = exchange.getResponse();
	assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertThat(response.getHeaders().get(VARY), contains(ORIGIN,
			ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS));
	assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
}
 
Example 14
Source File: DefaultCorsProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void preflightRequestMatchedAllowedMethod() throws Exception {
	ServerWebExchange exchange = MockServerWebExchange.from(
			preFlightRequest().header(ACCESS_CONTROL_REQUEST_METHOD, "GET"));
	this.conf.addAllowedOrigin("*");
	this.processor.process(this.conf, exchange);

	ServerHttpResponse response = exchange.getResponse();
	assertNull(response.getStatusCode());
	assertThat(response.getHeaders().get(VARY), contains(ORIGIN,
			ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS));
	assertEquals("GET,HEAD", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS));
}
 
Example 15
Source File: TomcatRequestUpgradeStrategy.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler,
		@Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory){

	ServerHttpRequest request = exchange.getRequest();
	ServerHttpResponse response = exchange.getResponse();

	HttpServletRequest servletRequest = getHttpServletRequest(request);
	HttpServletResponse servletResponse = getHttpServletResponse(response);

	HandshakeInfo handshakeInfo = handshakeInfoFactory.get();
	DataBufferFactory bufferFactory = response.bufferFactory();

	Endpoint endpoint = new StandardWebSocketHandlerAdapter(
			handler, session -> new TomcatWebSocketSession(session, handshakeInfo, bufferFactory));

	String requestURI = servletRequest.getRequestURI();
	DefaultServerEndpointConfig config = new DefaultServerEndpointConfig(requestURI, endpoint);
	config.setSubprotocols(subProtocol != null ?
			Collections.singletonList(subProtocol) : Collections.emptyList());

	try {
		WsServerContainer container = getContainer(servletRequest);
		container.doUpgrade(servletRequest, servletResponse, config, Collections.emptyMap());
	}
	catch (ServletException | IOException ex) {
		return Mono.error(ex);
	}

	return Mono.empty();
}
 
Example 16
Source File: DefaultCorsProcessorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void preflightRequestWithoutRequestMethod() throws Exception {
	ServerWebExchange exchange = MockServerWebExchange.from(
			preFlightRequest().header(ACCESS_CONTROL_REQUEST_HEADERS, "Header1"));
	this.processor.process(this.conf, exchange);

	ServerHttpResponse response = exchange.getResponse();
	assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
	assertThat(response.getHeaders().get(VARY), contains(ORIGIN,
			ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS));
	assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
}
 
Example 17
Source File: WrapperResponseFilter.java    From gateway with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 响应消息输出过滤器
 *
 * @param exchange ServerWebExchange
 * @param chain    GatewayFilterChain
 * @return Mono
 */
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpResponse originalResponse = exchange.getResponse();
    ServerHttpResponseDecorator responseDecorator = new ServerHttpResponseDecorator(originalResponse) {

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

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

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

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

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

            return super.writeWith(body);
        }
    };
    // replace response with decorator
    return chain.filter(exchange.mutate().response(responseDecorator).build());
}
 
Example 18
Source File: RouteEnhanceServiceImpl.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> filterRateLimit(ServerWebExchange exchange) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    ServerHttpRequest request = exchange.getRequest();
    ServerHttpResponse response = exchange.getResponse();
    try {
        URI originUri = getGatewayOriginalRequestUrl(exchange);
        if (originUri != null) {
            String requestIp = FebsUtil.getServerHttpRequestIpAddress(request);
            String requestMethod = request.getMethodValue();
            AtomicBoolean limit = new AtomicBoolean(false);
            Object o = routeEnhanceCacheService.getRateLimitRule(originUri.getPath(), METHOD_ALL);
            if (o == null) {
                o = routeEnhanceCacheService.getRateLimitRule(originUri.getPath(), requestMethod);
            }
            if (o != null) {
                RateLimitRule rule = JSONObject.parseObject(o.toString(), RateLimitRule.class);
                Mono<Void> result = doRateLimitCheck(limit, rule, originUri, requestIp, requestMethod, response);
                log.info("Rate limit verification completed - {}", stopwatch.stop());
                if (result != null) {
                    return result;
                }
            }
        } else {
            log.info("Request IP not obtained, no rate limit filter - {}", stopwatch.stop());
        }
    } catch (Exception e) {
        log.warn("Current limit failure : {} - {}", e.getMessage(), stopwatch.stop());
    }
    return null;
}
 
Example 19
Source File: ApiProxyController.java    From demo-spring-webflux-api-gateway with Apache License 2.0 4 votes vote down vote up
/**
    * 
    * @param exchange 
    * @return
    */
   @RequestMapping("/**")
   public Mono<Void>  proxyRequest(ServerWebExchange exchange)
{
	ServerHttpRequest frontEndReq = exchange.getRequest();
	ServerHttpResponse frontEndResp = exchange.getResponse();
	String path = frontEndReq.getPath().pathWithinApplication().value();
	HttpMethod httpMethod = frontEndReq.getMethod();
	RequestBodySpec reqBodySpec = webClient.method(httpMethod).
			uri(backendServiceUrlPrefix.concat(path)).
			headers(httpHeaders -> 
			        {
	                  httpHeaders.addAll(frontEndReq.getHeaders());
	                  httpHeaders.remove("HOST");
	                });
	
	RequestHeadersSpec<?> reqHeadersSpec;
    if (requireHttpBody(httpMethod)) {
    		  reqHeadersSpec = reqBodySpec.body(BodyInserters.fromDataBuffers(frontEndReq.getBody()));
    } else {
    	      reqHeadersSpec = reqBodySpec;
    	}
    
	//调用后端服务
	return reqHeadersSpec.exchange().timeout(Duration.ofMillis(backendServiceTimeoutInMillis)).
			onErrorResume(ex -> 
		    { 
			    //调用后端服务异常(超时、网络问题)时,转发到后端异常-后控制器
		    	    //此处也可不用转发,用frontEndResp.writeWith(...)直接将异常响应写回给调用方
		    	    Map<String,Object> forwardAttrs = new HashMap<>();
		    	    forwardAttrs.put(Constant.BACKEND_EXCEPTION_ATTR_NAME,ex);
                return WebfluxForwardingUtil.forward(Constant.BACKEND_EXCEPTION_PATH,exchange,forwardAttrs)
                		.then(Mono.empty());
			}).flatMap(backendResponse -> 
		    {
		    	    //将后端服务的响应回写到前端resp
		    	    frontEndResp.setStatusCode(backendResponse.statusCode());
		    	    frontEndResp.getHeaders().putAll(backendResponse.headers().asHttpHeaders());
		    	    return frontEndResp.writeWith(backendResponse.bodyToFlux(DataBuffer.class));
		    	}
		    	);
}
 
Example 20
Source File: AuthFilter.java    From light-reading-cloud with MIT License 4 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    // 白名单Path
    Set<String> whiteList = this.getWhiteList();
    String path = exchange.getRequest().getPath().toString();

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

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

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

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