PS:
response.setComplete();// 加上这个会使得前端取不到返回值,其content-length = 0
package xyz.haishui.offer.gateway.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import xyz.haishui.offer.common.RestResult;
import xyz.haishui.offer.gateway.config.AuthFilterConfig;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Component
public class AuthFilter implements GlobalFilter, Ordered {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private AuthFilterConfig authFilterConfig;
@Override
public int getOrder() {
return 1;
}
/**
* Process the Web request and (optionally) delegate to the next {@code WebFilter}
* through the given {@link GatewayFilterChain}.
*
* @param exchange the current server exchange
* @param chain provides a way to delegate to the next filter
* @return {@code Mono<Void>} to indicate when request processing is complete
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
if (!authFilterConfig.isEnable()){
return chain.filter(exchange);
}
URI uri = exchange.getRequest().getURI();
if (authFilterConfig.getCheckUrls().stream().anyMatch(
url -> uri.getPath().matches(url)
)){
// 检查token
List<String> authorizationList = exchange.getRequest().getHeaders().get("Authorization");
if (authorizationList==null||authorizationList.size()==0){
return errorReturn(exchange.getResponse());
}
logger.debug("检查token");
}
return chain.filter(exchange);
}
/**
* token检验不通过
* @param response ServerHttpResponse
* @return 写入错误提示并结束过滤链条,返回给前端
*/
private Mono<Void> errorReturn(ServerHttpResponse response){
String data=new RestResult<String>().unauthorized().msg("请登录").toString();
byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = response.bufferFactory().wrap(bytes);
response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
// response.setComplete();// 加上这个会使得前端取不到返回值,其content-length = 0
response.setStatusCode(HttpStatus.OK);
return response.writeWith(Mono.just(buffer));
}
}