gateway网关过滤验证请求头然后追加请求头
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String url = exchange.getRequest().getURI().getPath();
log.info("请求地址:"+url);
if(emergentNoticeProperties.getEmergentFlag()){
throw new SystemEmergentException(ExceptionCode.SYSTEM_EMERGENT_NOTICE.getCode(),String.format("%s,请稍等%s分钟再试",emergentNoticeProperties.getMsg(),emergentNoticeProperties.getMinute()));
}
String traceId = UUID.randomUUID().toString();
log.info("请求链路ID:"+traceId);
log.info("登录的token 的key是:{}",getTokenKey(token));
// 从缓存中取login_tokens:token的数据
String userStr = sops.get(getTokenKey(token));
if (StringUtils.isBlank(userStr)){
return setUnauthorizedResponse(exchange,ExceptionCode.TOKEN_ISNOT_VALID.getCode(), "登录状态已过期");
}
//注意:网关最好不要依赖其他库,否则容易引发包冲突,因此采用JsonObject解析。
JSONObject obj = JSONObject.parseObject(userStr);
String from = obj.getString("from");
String appCode = obj.getString("appCode");
// 由于现在使用id的是雪花算法 所以这里要改成getLong
String userid = obj.getLong("userId").toString();
if (null==userid || StringUtils.isBlank(from) || StringUtils.isBlank(appCode)){
return setUnauthorizedResponse(exchange, ExceptionCode.AUTHENTICATION_EXCEPTION.getCode(), "令牌验证失败");
}
// 设置过期时间
redisService.expire(getTokenKey(token), EXPIRE_TIME);
//设置用户信息到请求,注意,这里是追加头部信息,token信息已经有了
ServerHttpRequest mutableReq = exchange.getRequest().mutate().header(CacheConstants.DETAILS_USER_ID, userid)
.header(CacheConstants.DETAILS_CLIENIT, from).header(CacheConstants.DETAILS_FROM_APP,appCode)
.header(CacheConstants.REQUEST_TRACE,traceId).build();
ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
return chain.filter(mutableExchange);
}
}