gateway网关拦截
2020-09-08 本文已影响0人
半日孤独
实现 GlobalFilter, Ordered
@Component
@Slf4j
public class MyGateWayFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String token = request.getHeaders().getFirst("X-token");
if (("/api/login").equals(request.getURI().getPath())) {
//登录接口,通过
return chain.filter(exchange);
}
// 如果请求头不存在 Token
if (token == null) {
return this.getResponseError(exchange, "token不能为空,请重新登录");
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
拦截失败自定义返回错误信息
private Mono<Void> getResponseError(ServerWebExchange exchange, String msg) {
ServerHttpResponse response = exchange.getResponse();
JSONObject message = new JSONObject();
message.put("code", -1);
message.put("message", msg);
byte[] bits = message.toJSONString().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));
}