spring cloud gateway中请求过滤器
package com.zmx.gateway.filter;
import com.zmx.gateway.properties.MallAuthProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
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.data.redis.core.RedisTemplate;
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.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.*;
/**
* @Description: 登录过滤器, 校验token是否有效
* @ClassName: MallAuth
* @Author zhaomxr
* @Date 2021-11-02 10:23
*/
@Slf4j
@Component
public class MallAuthFilter implements GlobalFilter, Ordered {
private final static String AUTHORIZATION = "Authorization";
private final static String COOKIE = "Cookies";
private final static String PREFIX_TOKEN = "token_";
private static String requestUrl = "";
private static String cookies = "";
private static String token = "";
@Autowired
private MallAuthProperties mallAuthProperties;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private SendRequestLog sendRequestLogListener;
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//request参数
ServerHttpRequest request = exchange.getRequest();
if (shouldFilter(request)) {
//直接拒绝
log.info("用户未登录或登录已经超时过期。");
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
DataBuffer bodyDataBuffer = response.bufferFactory().wrap("auth check error".getBytes());
response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
return response.writeWith(Mono.just(bodyDataBuffer));
}
//异步 记录所有请求日志
sendRequestLogListener.send(requestUrl, token, cookies);
//通过这个过滤器,进入过滤链中的下一个过滤器
return chain.filter(exchange);
}
private boolean shouldFilter(ServerHttpRequest request) {
requestUrl = request.getPath().value();
log.info("requestUrl: {}", requestUrl);
//如果开启指定url忽略过滤
if (mallAuthProperties.isEnabled()) {
//如果请求路径与指定忽略url匹配则跳过
Set<String> ignoreUrls = mallAuthProperties.getIgnoreUrls();
for (String ignoreUrl : ignoreUrls) {
if (match(ignoreUrl, requestUrl)) {
return false;
}
}
}
// 判断是否为对外提供的接口,即client中接口
String sysCode = request.getHeaders().getFirst("sys_code");
if (StringUtils.isNotBlank(sysCode)) {
return false;
}
String authorization = request.getHeaders().getFirst(AUTHORIZATION);
cookies = request.getHeaders().getFirst(COOKIE);
log.info("authorization: {}, cookies: {}", authorization, cookies);
//判断请求头中token或者cookies是否为空
if (StringUtils.isEmpty(authorization) || StringUtils.isEmpty(cookies)) {
return true;
}
//判断请求头中token是否为标准bearer token,且token值不能为空
String[] tokens = authorization.split(" ");
if (tokens.length != 2 || StringUtils.isEmpty(tokens[1])) {
return true;
}
token = tokens[1];
String[] cookieList = cookies.split(";");
Map<String, String> cookieMap = new HashMap<String, String>(cookieList.length);
Arrays.stream(cookieList).forEach(s -> {
String[] split = s.split("=");
if (!cookieMap.containsKey(split[0])) {
cookieMap.put(split[0], split[1]);
}
});
Object redisToken = redisTemplate.opsForValue().get(PREFIX_TOKEN + cookieMap.get("userId"));
Object redis = redisTemplate.opsForValue().get("token_1");
log.info("redisToken:{}, redis {}", redisToken, redis);
//如果redis中token不存在或者与当前token不相等,则认为当前用户登录已失效
// if (redisToken == null || !Objects.equals(token, redisToken)) {
// return true;
// }
return false;
}
private boolean match(String ignoreUrl, String requestUrl) {
PathMatcher pathMatcher = new AntPathMatcher();
return pathMatcher.match(ignoreUrl, requestUrl);
}
public int getOrder() {
return 0;
}
}