java – 如何在Cloud Api Gateway的响应体中添加一些数据
作者:互联网
我在云api网关中添加了一些auth逻辑.我添加了GatewayFilter:
import java.util.List;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PatternMatchUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
public class AuthorizationFilter implements GatewayFilter {
@Override
public Mono<Void> filter(
ServerWebExchange exchange, GatewayFilterChain chain) {
List<String> authorization = exchange.getRequest().getHeaders().get("Authorization");
if (CollectionUtils.isEmpty(authorization) &&
!PatternMatchUtils.simpleMatch(URL_WITHOUT_AUTH, exchange.getRequest().getURI().toString())) {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
//Add some custom data in body of the response
return exchange.getResponse().setComplete();
}
String token = authorization.get(0).split(" ")[1];
// token validation
return chain.filter(exchange);
}
}
但是我无法在响应体中添加一些数据.你能帮助我找出它的工作原理以及我如何定制它吗?
附:
我正在尝试使用flux添加一些数据,但它不起作用:
DataBuffer b = exchange.getResponse().bufferFactory().allocateBuffer(256);
b.write("12345".getBytes());
return exchange.getResponse().writeWith(s -> Flux.just(b));
我做错了什么?
解决方法:
在春天的帮助下,我能够让它发挥作用.因此,不必直接写入响应,而是必须抛出自定义异常并正确处理它:
@Bean
public ErrorWebExceptionHandler myExceptionHandler() {
return new MyWebExceptionHandler();
}
public class MyWebExceptionHandler implements ErrorWebExceptionHandler {
@Override
public Mono<Void> handle(
ServerWebExchange exchange, Throwable ex) {
byte[] bytes = "Some text".getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
return exchange.getResponse().writeWith(Flux.just(buffer));
}
}
标签:java,spring,spring-cloud-2 来源: https://codeday.me/bug/20190701/1347823.html