Commit 9d27b0a5 by 刘宇峰

优化代码

1 parent ada8d7d1
......@@ -41,7 +41,7 @@ import java.util.*;
* @author payu
*/
@Slf4j
@Component
//@Component
public class CheckSignGlobalFilter implements GlobalFilter, Ordered {
@Autowired
......@@ -64,9 +64,7 @@ public class CheckSignGlobalFilter implements GlobalFilter, Ordered {
return chain.filter(exchange);
}
Map<String, String> params = new HashMap<>();
request.getQueryParams().forEach((key, items) -> {
params.put(key, items.get(0));
});
request.getQueryParams().forEach((key, items) -> params.put(key, items.get(0)));
String sign = request.getHeaders().getFirst("sign");
params.put("sign", sign);
if (HttpMethod.GET.name().equals(request.getMethodValue())) {
......
package cn.com.glsx.gateway.filter;
import cn.com.glsx.auth.model.GatewayService;
import com.alibaba.fastjson.JSON;
import com.glsx.plat.core.web.R;
import cn.com.glsx.gateway.common.Constants;
import cn.com.glsx.gateway.utils.GatewayIpUtils;
import com.alibaba.fastjson.JSON;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
......@@ -14,12 +15,11 @@ import org.springframework.core.Ordered;
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 reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
* @author huangch
......@@ -34,7 +34,7 @@ import java.util.Objects;
@RefreshScope
public class IPCheckGlobalFilter implements GlobalFilter, Ordered {
@Value("${gateway.skip.urls:#{null}}")
@Value("${gateway.skipAuth.urls:#{null}}")
private String[] skipAuthUrls;
@Override
......@@ -42,19 +42,21 @@ public class IPCheckGlobalFilter implements GlobalFilter, Ordered {
ServerHttpRequest request = exchange.getRequest();
String url = exchange.getRequest().getURI().getPath();
//跳过不需要验证的路径
if (!Objects.isNull(skipAuthUrls) && Arrays.asList(skipAuthUrls).contains(url)) {
if (StringUtils.isMatchedStr(skipAuthUrls, url)) {
return chain.filter(exchange);
}
GatewayService gatewayService = exchange.getAttribute(Constants.GATEWAY_SERVICE_NAME);
// TODO: 2023/4/20
GatewayService gatewayService = exchange.getAttribute("");
//判断鉴权开关是否打开
if(!gatewayService.getIpAuth()){
if (!gatewayService.getIpAuth()) {
return chain.filter(exchange);
}
//获取请求方真实IP
String requestIp = GatewayIpUtils.getIpAddr(request);
//判断请求方IP是否在白名单内
List<String> whiteIps = Arrays.asList(gatewayService.getWhiteIps().split(","));
if(whiteIps.contains(requestIp)){
if (whiteIps.contains(requestIp)) {
return chain.filter(exchange);
}
ServerHttpResponse response = exchange.getResponse();
......
......@@ -6,10 +6,10 @@ import cn.com.glsx.auth.utils.GatewayJwtUtils;
import cn.com.glsx.gateway.common.Constants;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.core.web.R;
import com.glsx.plat.exception.SystemMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
......@@ -29,9 +29,6 @@ import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
......@@ -42,7 +39,7 @@ import java.util.Objects;
@RefreshScope
public class JWTAuthGlobalFilter implements GlobalFilter, Ordered {
@Value("${gateway.skip.urls:#{null}}")
@Value("${gateway.skipAuth.urls:#{null}}")
private String[] skipAuthUrls;
@Autowired
......@@ -63,21 +60,14 @@ public class JWTAuthGlobalFilter implements GlobalFilter, Ordered {
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String url = exchange.getRequest().getURI().getPath();
//跳过不需要验证的路径
if (!Objects.isNull(skipAuthUrls) && Arrays.asList(skipAuthUrls).contains(url)) {
if (StringUtils.isMatchedStr(skipAuthUrls, url)) {
return chain.filter(exchange);
}
//api接口不需要验证
String[] urlPaths = url.split("/");
if (!CollectionUtils.sizeIsEmpty(urlPaths)) {
List<String> list = new ArrayList<>(Arrays.asList(urlPaths));
if (list.contains("api") || list.contains("API")) {
return chain.filter(exchange);
}
}
//从请求头中取出org
String serName = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION + "-Org");
GatewayService gatewayService = apiGatewayServiceConfig.getServiceByName(serName);
if (!gatewayService.getJwtAuth()) {
if (!Objects.isNull(gatewayService) && !gatewayService.getJwtAuth()) {
return chain.filter(exchange);
}
......@@ -106,13 +96,12 @@ public class JWTAuthGlobalFilter implements GlobalFilter, Ordered {
public Mono<Void> loginResponse(ServerWebExchange exchange, String token) {
ServerHttpResponse originalResponse = exchange.getResponse();
originalResponse.setStatusCode(HttpStatus.OK);
originalResponse.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
originalResponse.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
originalResponse.getHeaders().add(HttpHeaders.FROM, "Gateway");
log.info("invalid token [{}]", token);
String notLoginJson = JSON.toJSONString(R.error(SystemMessage.NOT_LOGIN.getCode(), SystemMessage.NOT_LOGIN.getMsg()));
byte[] response = notLoginJson.getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = originalResponse.bufferFactory().wrap(response);
String notLoginJson = JSON.toJSONString(R.error(SystemMessage.PERMISSION_DENIED.getCode(), SystemMessage.PERMISSION_DENIED.getMsg()));
DataBuffer buffer = originalResponse.bufferFactory().wrap(notLoginJson.getBytes(StandardCharsets.UTF_8));
return originalResponse.writeWith(Flux.just(buffer));
}
......
package cn.com.glsx.gateway.filter;
import cn.com.glsx.auth.config.ApiGatewayServiceConfig;
import cn.com.glsx.auth.model.GatewayService;
import cn.com.glsx.auth.utils.GatewayJwtUtils;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
......@@ -34,10 +35,8 @@ import reactor.core.publisher.Mono;
import java.net.URI;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
@Slf4j
......@@ -45,7 +44,7 @@ import java.util.concurrent.atomic.AtomicReference;
@RefreshScope
public class OpenApiAuthCheckFilter implements GlobalFilter, Ordered {
@Value("${gateway.skip.urls:#{null}}")
@Value("${gateway.skipAuth.urls:#{null}}")
private String[] skipAuthUrls;
@Value("${gateway.openApi.urls:#{null}}")
......@@ -62,20 +61,13 @@ public class OpenApiAuthCheckFilter implements GlobalFilter, Ordered {
ServerHttpRequest serverHttpRequest = exchange.getRequest();
String url = exchange.getRequest().getURI().getPath();
//跳过不需要验证的路径
if (!Objects.isNull(skipAuthUrls) && Arrays.asList(skipAuthUrls).contains(url)) {
if (StringUtils.isMatchedStr(skipAuthUrls, url)) {
return chain.filter(exchange);
}
//跳过不符合需要验证的路径
if (!Objects.isNull(openApiUrls)) {
AtomicBoolean flag = new AtomicBoolean(false);
Arrays.asList(openApiUrls).forEach(apiUrl -> {
//全匹配或前缀匹配
flag.set(url.equals(apiUrl) || url.startsWith(apiUrl.replace("*", "")));
});
if (!flag.get()) {//不满足走下一个过滤器
return chain.filter(exchange);
}
if (StringUtils.isMatchedStr(openApiUrls, url)) {
return chain.filter(exchange);
}
String method = serverHttpRequest.getMethodValue();
......@@ -108,7 +100,10 @@ public class OpenApiAuthCheckFilter implements GlobalFilter, Ordered {
String serName = decodedJWT.getClaim("name").asString();
DecodedJWT verifyJWT = gatewayJwtUtils.verify(accessToken, apiGatewayServiceConfig.getServiceByName(serName));
GatewayService gatewayService = apiGatewayServiceConfig.getServiceByName(serName);
// TODO: 2023/4/20 gatewayService放入exchange,供后面filter使用
DecodedJWT verifyJWT = gatewayJwtUtils.verify(accessToken, gatewayService);
if (verifyJWT == null) {
return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(JSON.toJSONString(OpenApiResult.failure("40003", "AccessToken Error.")).getBytes())));
}
......
......@@ -30,7 +30,7 @@ import java.util.Objects;
//@Component
public class RecordServiceFilter implements GlobalFilter, Ordered {
@Value("${gateway.skip.urls:#{null}}")
@Value("${gateway.skipAuth.urls:#{null}}")
private String[] skipAuthUrls;
@Autowired
......
......@@ -92,7 +92,7 @@ public class XssRequestGlobalFilter implements GlobalFilter, Ordered {
log.error("请求异常:{} POST请求必须传递参数", serverHttpRequest.getURI().getRawPath());
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.BAD_REQUEST);
String notLoginJson = JSON.toJSONString(R.error(SystemMessage.NOT_LOGIN.getCode(), SystemMessage.NOT_LOGIN.getMsg()));
String notLoginJson = JSON.toJSONString(R.error(SystemMessage.PERMISSION_DENIED.getCode(), SystemMessage.PERMISSION_DENIED.getMsg()));
byte[] bytes = notLoginJson.getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = response.bufferFactory().wrap(bytes);
return response.writeWith(Mono.just(buffer));
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!