Spring Cloud Gateway 3.x 获取body中的数据鉴权
在Spring Cloud Gateway中,你可以通过定义一个全局过滤器来获取请求体中的数据并进行鉴权。以下是一个简单的示例,展示了如何在全局过滤器中读取请求体数据:
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
public class AuthGlobalFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 获取请求体
return DataBufferUtils.join(exchange.getRequest().getBody())
.flatMap(dataBuffer -> {
// 将数据缓冲区内容转换成字符串
byte[] bytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(bytes);
String body = new String(bytes, StandardCharsets.UTF_8);
// 这里可以添加鉴权逻辑,例如检查body中的token
// boolean isAuthenticated = authenticate(body);
// if (!isAuthenticated) {
// // 不通过鉴权,返回错误响应
// return Mono.defer(() -> Mono.error(new RuntimeException("Authentication failed")));
// }
// 重置请求体,以便后续过滤器可以正常读取
DataBufferUtils.release(dataBuffer);
Flux<DataBuffer> cachedFlux = Flux.defer(() -> Flux.just(bufferFactory.wrap(bytes)));
ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(exchange.getRequest()) {
@Override
public Flux<DataBuffer> getBody() {
return cachedFlux;
}
};
return chain.filter(exchange.mutate().request(decorator).build());
});
}
}
在上面
评论已关闭