spring cloud gateway WebFilter 比 GlobalFilter 早,并且 能作用于所有的 请求 包含 gateway项目里的 controller
ServerHttpResponse 没有body 只能从 DataBuffer里取 或者 放入
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
@Component
public class JWTFilters implements WebFilter {
private final Logger logger = LoggerFactory.getLogger(JWTFilters.class);
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
HttpCookie tokenCookie = exchange.getRequest().getCookies().getFirst("token");
logger.info("cookie {}", tokenCookie);
String pathStr = request.getPath().toString();
if (tokenCookie != null && !StrUtil.isBlank(tokenCookie.getValue())) {
// 校验 token
} else {
if (pathStr.startsWith("/login")) {
// 调用登录 验证
} else {
// 需要登录
ServerHttpResponse res = exchange.getResponse();
res.setStatusCode(HttpStatus.UNAUTHORIZED);
ObjectMapper resJSONMap = new ObjectMapper();
ObjectNode resJSON = resJSONMap.createObjectNode();
resJSON.put("retCode", "-1");
resJSON.put("retMsg", "认证失败,缺少token");
try {
// ServerHttpResponse 没有body 只能从 DataBuffer里取 或者 放入
String resStr = resJSONMap.writerWithDefaultPrettyPrinter().writeValueAsString(resJSON);
DataBuffer db = res.bufferFactory().wrap(resStr.getBytes(StandardCharsets.UTF_8));
return res.writeWith(Mono.just(db));
} catch (JsonProcessingException e) {
logger.info("JSON 转换失败: {0}", e);
throw new RuntimeException(e);
}
}
}
logger.info(request.getPath().toString());
logger.info("JWT Filters");
return chain.filter(exchange);
}
}