Spring Cloud Zuul如何实现开放平台接口的拦截校验(下)

简介: Spring Cloud Zuul如何实现开放平台接口的拦截校验

【校验请求参数】

我们在校验请求参数的实现中使用了策略模式,目前只支持GETPOST请求,代码如下:

import javax.servlet.http.HttpServletRequest;
/**
 * @author zouwei
 * @className MethodSecurityStrategy
 * @date: 2020/11/25 上午11:45
 * @description:
 */
public interface MethodSecurityStrategy {
    String JOIN_STR = "&";
    boolean test(HttpServletRequest request, String securityKey);
    boolean isTest(String requestMethod);
}
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.netflix.zuul.context.RequestContext;
import com.zx.silverfox.common.config.api.ApiSecurityConst;
import com.zx.silverfox.common.util.CastUtil;
import com.zx.silverfox.common.util.JsonUtil;
import com.zx.silverfox.common.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StreamUtils;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.*;
/**
 * @author zouwei
 * @className AbstractMethodSecurityStrategy
 * @date: 2020/11/25 下午4:07
 * @description:
 */
@Slf4j
public abstract class AbstractMethodSecurityStrategy implements MethodSecurityStrategy {
    @Override
    public boolean test(HttpServletRequest request, String securityKey) {
        // 名称需要排序
        String str = joinGetRequestParams(request);
        return checkSign(request, str, securityKey);
    }
    private String requestSign(HttpServletRequest request) {
        return request.getHeader(ApiSecurityConst.SIGN_KEY);
    }
    private String appKey(HttpServletRequest request) {
        return request.getHeader(ApiSecurityConst.API_KEY);
    }
    /**
     * 校验签名
     *
     * @param request 请求
     * @param str 需要加密的字符串
     * @param securityKey 加密密钥
     * @return
     */
    protected boolean checkSign(HttpServletRequest request, String str, String securityKey) {
        if (StringUtils.isBlank(str)) {
            return false;
        }
        // 通过securityKey加密
        String sign = MD5Util.macSha2Base64(str, securityKey);
        return StringUtils.equals(requestSign(request), sign);
    }
    /**
     * 拼接GET请求参数
     *
     * @param request
     * @return
     */
    protected String joinGetRequestParams(HttpServletRequest request) {
        Enumeration<String> enumeration = request.getParameterNames();
        List<String> list = Lists.newArrayList();
        while (enumeration.hasMoreElements()) {
            list.add(enumeration.nextElement());
        }
        Collections.sort(list);
        StringJoiner sj = new StringJoiner(JOIN_STR);
        for (String name : list) {
            String value = request.getParameter(name);
            sj.add(name + "=" + value);
        }
        sj.add("appKey=" + appKey(request));
        return sj.toString();
    }
    /**
     * 拼接POST请求参数
     *
     * @param request
     * @return
     */
    protected String joinPostRequestParams(HttpServletRequest request) {
        String requestBody;
        try {
            BodyReaderHttpServletRequestWrapper requestWrapper =
                    new BodyReaderHttpServletRequestWrapper(request);
            RequestContext currentContext = RequestContext.getCurrentContext();
            requestBody = requestWrapper.getBody();
            currentContext.setRequest(requestWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return StringUtils.EMPTY;
        }
        Map<String, Object> map = JsonUtil.string2Obj(requestBody, Map.class);
        // 准备排序
        TreeMap<String, Object> treeMap = Maps.newTreeMap();
        if (Objects.nonNull(map)) {
            treeMap.putAll(map);
        }
        // 获取parameter
        Enumeration<String> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            treeMap.put(key, request.getParameter(key));
        }
        // 拼接字符串
        StringJoiner sj = new StringJoiner(JOIN_STR);
        for (Map.Entry<String, Object> e : treeMap.entrySet()) {
            String name = e.getKey();
            String value = CastUtil.castString(e.getValue());
            sj.add(name + "=" + value);
        }
        sj.add("appKey=" + appKey(request));
        return sj.toString();
    }
    public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
        private final byte[] bodyBytes;
        private final String body;
        public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
            super(request);
            this.bodyBytes = StreamUtils.copyToByteArray(request.getInputStream());
            body = new String(this.bodyBytes, Charset.forName("UTF-8"));
        }
        public String getBody() {
            return this.body;
        }
        @Override
        public BufferedReader getReader() throws IOException {
            return new BufferedReader(new InputStreamReader(getInputStream()));
        }
        @Override
        public int getContentLength() {
            return this.bodyBytes.length;
        }
        @Override
        public long getContentLengthLong() {
            return this.bodyBytes.length;
        }
        @Override
        public ServletInputStream getInputStream() throws IOException {
            final ByteArrayInputStream bais = new ByteArrayInputStream(bodyBytes);
            return new ServletInputStream() {
                @Override
                public boolean isFinished() {
                    return false;
                }
                @Override
                public boolean isReady() {
                    return true;
                }
                @Override
                public void setReadListener(ReadListener listener) {}
                @Override
                public int read() throws IOException {
                    return bais.read();
                }
            };
        }
    }
}
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
/**
 * @author zouwei
 * @className GetSecurityStrategy
 * @date: 2020/11/25 上午11:45
 * @description:
 */
@Component
public class GetSecurityStrategy extends AbstractMethodSecurityStrategy
        implements MethodSecurityStrategy {
    @Override
    public boolean isTest(String requestMethod) {
        return StringUtils.equalsIgnoreCase(requestMethod, HttpMethod.GET.name());
    }
}
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
/**
 * @author zouwei
 * @className GetSecurityStrategy
 * @date: 2020/11/25 上午11:45
 * @description:
 */
@Component
public class PostSecurityStrategy extends AbstractMethodSecurityStrategy
        implements MethodSecurityStrategy {
    @Override
    public boolean test(HttpServletRequest request, String securityKey) {
        // 解析请求体
        String str = joinPostRequestParams(request);
        // 校验签名
        return checkSign(request, str, securityKey);
    }
    @Override
    public boolean isTest(String requestMethod) {
        return StringUtils.equalsIgnoreCase(requestMethod, HttpMethod.POST.name());
    }
}
复制代码

【组装请求】

在请求被网关解开后,是不能继续向后传递的,那么网关需要重新组装一个请求对象并把之前取出来的数据放进去,这样才能让用户的请求继续向后传递;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zx.silverfox.common.util.CastUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;
/**
 * @author zouwei
 * @className CustomHeaderServletRequest
 * @date: 2020/9/24 下午1:48
 * @description:
 */
public class CustomHeaderServletRequest extends HttpServletRequestWrapper {
    private Map<String, String> headers = Maps.newHashMap();
    public CustomHeaderServletRequest(HttpServletRequest request) {
        super(request);
    }
    public void setHeaders(String key, String value) {
        headers.put(key, value);
    }
    private HttpServletRequest _getHttpServletRequest() {
        return (HttpServletRequest) super.getRequest();
    }
    @Override
    public String getHeader(String name) {
        String value = this._getHttpServletRequest().getHeader(name);
        if (StringUtils.isBlank(value)) {
            return this.headers.get(name);
        }
        return value;
    }
    @Override
    public Enumeration<String> getHeaders(String name) {
        Enumeration<String> values = this._getHttpServletRequest().getHeaders(name);
        String value = this.headers.get(name);
        if (StringUtils.isBlank(value)) {
            return values;
        }
        Collection<String> collection = Lists.newArrayList();
        collection.add(value);
        while (values.hasMoreElements()) {
            collection.add(values.nextElement());
        }
        return Collections.enumeration(collection);
    }
    @Override
    public Enumeration<String> getHeaderNames() {
        Enumeration<String> values = this._getHttpServletRequest().getHeaderNames();
        Set<String> keys = this.headers.keySet();
        if (CollectionUtils.isEmpty(keys)) {
            return values;
        }
        Collection<String> collection = Lists.newArrayList();
        while (values.hasMoreElements()) {
            collection.add(values.nextElement());
        }
        collection.addAll(keys);
        return Collections.enumeration(collection);
    }
    @Override
    public long getDateHeader(String name) {
        long value = this._getHttpServletRequest().getDateHeader(name);
        if (value <= -1) {
            return CastUtil.castInt(headers.get(name), -1);
        }
        return value;
    }
    /**
     * The default behavior of this method is to return getIntHeader(String name) on the wrapped
     * request object.
     */
    @Override
    public int getIntHeader(String name) {
        int value = this._getHttpServletRequest().getIntHeader(name);
        if (value <= -1) {
            return CastUtil.castInt(headers.get(name), -1);
        }
        return value;
    }
}
复制代码

我们通过继承HttpServletRequestWrapper类来实现一个自定义的请求类,来根据元数据可以重新创建一个请求,这样的话,才能让用户请求继续传递下去。

小结

我们为了保证开放平台api的安全性,需要在网关针对特性请求进行拦截来校验,根据以上代码演示及概述,我们可以做出如下小结:

1.开放平台需要把对应的appKeyappSecret给到调用方;

2.调用方需要使用appKeyappSecret针对请求参数进行加密,得到加密结果sign并放到请求头中;

3.开发平台接收到请求后,判断是否是特定请求,如果属于需要拦截的请求,那么取出appKey去数据表中查询是否确实存在对应的权限,并同时查询出数据表中的appSecret;如果数据表中查询不到,那么说明没有访问权限;

4.开放平台同时还要拿出请求参数,并通过appKeyappSecret进行同样的加密操作得到sign结果,并与请求头中拿到的sign进行对比;如果两者一致,权限通过;否则没有访问权限;

5.权限处理完毕后,需要重新组装请求继续向后传递,这里需要通过自定义请求来处理;


相关文章
|
4天前
|
监控 Java API
Spring cloud Hystrix 、Dashboard、API(zuul)相关报错
Spring cloud Hystrix 、Dashboard、API(zuul)相关报错
18 2
|
2天前
|
消息中间件 Java 数据安全/隐私保护
Spring Cloud 项目中实现推送消息到 RabbitMQ 消息中间件
Spring Cloud 项目中实现推送消息到 RabbitMQ 消息中间件
|
2天前
|
负载均衡 监控 Java
我把Spring Cloud的超详细资料介绍给你,面试官不会生气吧?geigei
我把Spring Cloud的超详细资料介绍给你,面试官不会生气吧?geigei
|
3天前
|
负载均衡 Java 应用服务中间件
Spring Cloud 负载平衡的意义什么?
负载平衡是指将网络流量在多个服务器之间分布,以达到提高系统性能、增强可靠性和提供更好用户体验的目的。在负载平衡的架构中,多个服务器被组织成一个集群,共同处理用户的请求。
26 4
|
4天前
|
监控 安全 Java
Spring cloud原理详解
Spring cloud原理详解
18 0
|
4天前
|
Java Spring
spring boot访问接口报500
spring boot访问接口报500
13 2
|
4天前
|
消息中间件 负载均衡 Java
【Spring Cloud 初探幽】
【Spring Cloud 初探幽】
16 1
|
4天前
|
安全 Java Docker
|
4天前
|
Java 开发者 微服务
Spring Cloud原理详解
【5月更文挑战第4天】Spring Cloud是Spring生态系统中的微服务框架,包含配置管理、服务发现、断路器、API网关等工具,简化分布式系统开发。核心组件如Eureka(服务发现)、Config Server(配置中心)、Ribbon(负载均衡)、Hystrix(断路器)、Zuul(API网关)等。本文讨论了Spring Cloud的基本概念、核心组件、常见问题及解决策略,并提供代码示例,帮助开发者更好地理解和实践微服务架构。此外,还涵盖了服务通信方式、安全性、性能优化、自动化部署、服务网格和无服务器架构的融合等话题,揭示了微服务架构的未来趋势。
38 6
|
4天前
|
JSON Java Apache
Spring Cloud Feign 使用Apache的HTTP Client替换Feign原生httpclient
Spring Cloud Feign 使用Apache的HTTP Client替换Feign原生httpclient

热门文章

最新文章