1、鉴权filter
package com.pojo.gateway.filter;
import com.alibaba.fastjson.JSON;
import com.pojo.common.core.constant.CacheConstant;
import com.pojo.common.core.constant.Constants;
import com.pojo.common.core.domain.LoginUser;
import com.pojo.common.core.domain.ResponseResult;
import com.pojo.common.core.utils.StringUtils;
import com.pojo.gateway.config.properties.IgnoreWhiteProperties;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
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.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* 网关鉴权
*
* @author admin
*/
@Component
public class AuthFilter implements GlobalFilter, Ordered {
private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);
private final static long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;
// 排除过滤的 uri 地址,nacos自行添加
@Autowired
IgnoreWhiteProperties ignoreWhite;
@Autowired
RedissonClient redissonClient;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String url = request.getURI().getPath();
// 跳过不需要验证的路径
List<String> whitesUrl = ignoreWhite.getWhites();
if (whitesUrl.contains(url)) {
return chain.filter(exchange);
}
String token = "";
token = getToken(request);
if (StringUtils.isBlank(token)) {
log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
log.error("token 为空");
return setUnauthorizedResponse(exchange, 3000, "登录状态已过期");
}
RBucket<LoginUser> loginUserRBucket = redissonClient.getBucket(token);
LoginUser loginUser = loginUserRBucket.get();
if (Objects.isNull(loginUser)) {
log.error("登录状态已过期");
return setUnauthorizedResponse(exchange, 3000, "登录状态已过期");
}
String userId = loginUser.getUserId();
String userName = loginUser.getUserName();
String loginName = loginUser.getLoginN