springcloudgateway过滤器添加header信息验证请求来自网关

/ 小问题积累 / 0 条评论 / 810浏览
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    RedisTemplate<Object,Object> redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        String path = request.getURI().getPath();
        String wholeUrl = request.getURI().toString();
        String token = (String)UrlUtil.getParameter(wholeUrl).get("token");
        String authValue = CommonUtil.getRandomStr(8);
//        加入缓存
        RedisUtils<Object> redisUtils = new RedisUtils<>(redisTemplate);
        redisUtils.set(ApiGlobalConstants.AUTH_HEADER_REDIS_KEY,authValue,60*5);

        //加入请求头
        ServerHttpRequest newRequest = request.mutate().header(ApiGlobalConstants.AUTH_HEADER_REDIS_KEY, authValue).build();
............
        return chain.filter(exchange.mutate().request(newRequest.mutate().build()).build());
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response) {
        JSONObject message = new JSONObject();
        message.put("success",false);
        message.put("code",4004);
        message.put("data","鉴权失败");
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码,防止中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
服务中设置拦截器判断请求头的数据,从而判断是否为经过网关的请求

public class VerifyHeaderWhetherInRedisInterceptor implements HandlerInterceptor {


    @Autowired
    RedisTemplate<Object, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头标识和redis中标识
        String authValueInHeader = request.getHeader(ApiGlobalConstants.AUTH_HEADER_REDIS_KEY);
        RedisUtils<String> redisUtils = new RedisUtils<String>(redisTemplate);
        String authValueInRedis = redisUtils.get(ApiGlobalConstants.AUTH_HEADER_REDIS_KEY);

        //如果非网关请求
        if (CommonUtil.isEmpty(authValueInHeader) || !(authValueInHeader.equals(authValueInRedis))) {
            RespBody respBody = RespBody.fail().code(RespCode.ILLEGAL_REQUEST).httpStatus(HttpStatus.FORBIDDEN.value()).message(RespCode.ILLEGAL_REQUEST);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(JSONObject.toJSONString(respBody, SerializerFeature.WriteMapNullValue));
            return false;
        }
        return true;
    }
}