巧談數據接口安全-具體實現

巧談數據接口安全-具體實現

上一節針對數據接口的安全性提出瞭解決方式, 這節經過具體的代碼來實現web

巧談數據接口安全-理論篇redis

項目環境

項目接口採用SSM的框架, 基於SpringMVC攔截器來實現。 固然, 也能夠採用Spring的AOP來實現, 這種方式更通用一些spring

上代碼

本項目採用 SpringMVC攔截器的方式來實現json

獲取參數

目前接口最通用的提交方式是application/json, 這種方式在攔截器中若是要獲取POST方式的參數, 須要就其進行處理。後端

工具類 對獲得的參數進行處理spring-mvc

public class ParamUtils {
    private static final WeakHashMap<String, String> PARAMS = new WeakHashMap<>();
    public static final String KEY = "params";
    private ParamUtils() {
    }

    public static ParamUtils getInstance() {
        return ParamUtils.Holder.INSTANCE;
    }

    static class Holder {
        private static final ParamUtils INSTANCE = new ParamUtils();
    }

    /**
     * 將從post中獲取到的傳遞 存放到map中
     * @param params
     */
    public void set(String params) {
        PARAMS.put(KEY, params);
    }

    /**
     * 獲得json字符串
     * @return
     */
    public String get() {
        return PARAMS.get(KEY);
    }

    /**
     * 將json字符串轉換成map對象
     * @param json
     * @return
     */
    public Map<String, Object> json2Map(String json) {
        return (Map<String, Object>) JSON.parse(json);
    }

    /**
     * 簽名驗證
     * @param map
     * @return
     */
    public String getSign(Map<String, Object> map) {
        return getSign2Map(map);
    }

    private String getSign2Map(Map<String, Object> map) {
        StringBuffer sb = new StringBuffer();
        ArrayList<String> list = new ArrayList<String>(map.keySet());
        Collections.sort(list);

        for(String key:list) {
            Object value = map.get(key);
            if(!key.equalsIgnoreCase("sign"))
                sb.append(key).append("=").append(map.get(key)).append("&");
        }
        sb.deleteCharAt(sb.length() - 1);
        return DigestUtil.getInstance().md5(sb.toString());
    }

    public String getSign(String json){
        Map<String, Object> map = json2Map(json);
        return getSign2Map(map);
    }

    /**
     * 從get請求中獲取到參數 封裝成Map對象
     * @param request
     * @return
     */
    public Map<String, Object> getParam2Get(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();

        if(parameterMap != null && !parameterMap.isEmpty()) {
            for(Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                String[] value = entry.getValue();
                if(value != null && value.length > 0) {
                    map.put(entry.getKey(), value[0]);
                }
            }
        }

        return map;
    }
}
複製代碼

Filter 獲取非GET方式傳遞的數據安全

經過實現Filter的方式, 對非GET的request進行重寫, 獲得提交參數bash

public class SecurityFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        SecurityHttpServletRequestWrapper wrap = null;
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            if (!"get".equals(httpServletRequest.getMethod().toUpperCase()) 
                && httpServletRequest.getHeader("Accept").contains("application/json")) {
                wrap = new SecurityHttpServletRequestWrapper(httpServletRequest);
                ParamUtils.getInstance().set(wrap.getJson());
            }
        }
        if (null != wrap) {
            chain.doFilter(wrap, response);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}


class SecurityHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private String json;

    public SecurityHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        ServletInputStream stream = this.getRequest().getInputStream();
        json = IOUtils.toString(stream, "UTF-8");
    }

    @Override
    public ServletInputStream getInputStream() {
        byte[] buffer = null;
        try {
            buffer = json.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
        ServletInputStream newStream = new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bais.read();
            }
        };
        return newStream;
    }

    public String getJson() {
        return json;
    }

    public void setJson(String json) {
        this.json = json;
    }

}
複製代碼

web.xml中配置mvc

<filter>
    <filter-name>securityFilter</filter-name>
    <filter-class>com.sanq.product.security.filters.SecurityFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>securityFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
複製代碼

自定義過濾註解

在項目中 並非全部的接口都須要進行所有驗證的, 好比 登陸註冊這種的就不須要驗證Token, 這裏就須要將驗證過濾掉app

@IgnoreSecurity 過濾掉Token驗證

@Target(ElementType.METHOD) 
@Retention(RetentionPolicy.RUNTIME) 
@Documented
public @interface IgnoreSecurity {
}
複製代碼

@Security 過濾掉全部的驗證 (這裏名稱起的不是很好, 你們隨意替換)

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Security {
}
複製代碼

攔截匹配

到這裏, 咱們就應該在攔截器中開始咱們的攔截驗證了, 咱們在這裏須要驗證一下幾點:

  1. IP
  2. Token
  3. TimeStamp
  4. Sign
  5. Client 客戶端

首先咱們先將須要驗證的參數名稱寫入一個枚舉類中, 方便咱們查看

SecurityFieldEnum

public enum SecurityFieldEnum {
  //須要驗證的參數
  TOKEN("token"),
  TIMESTAMP("timestamp"),
  SIGN("sign"),
  CLIENT("client"),
  APP("APP");

  private String mName;

  SecurityFieldEnum(String name) {
      this.mName = name;
  }

  public String getName() {
      return mName;
  }
}
複製代碼

開始寫攔截器的代碼, 爲了能夠實現通用, 這裏定義爲abstract

SecurityInterceptor

public abstract class SecurityInterceptor implements HandlerInterceptor {

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


    if(handler instanceof HandlerMethod) {
        //驗證ip是否在黑名單中
        if(checkIp(request, GlobalUtil.getIpAddr(request))) {
            return false;
        }
        HandlerMethod hm = (HandlerMethod) handler;
        Security security = hm.getMethodAnnotation(Security.class);

        if (security != null) {
            return true;
        }

        IgnoreSecurity s = hm.getMethodAnnotation(IgnoreSecurity.class);

        Map<String, Object> objectMap;
        if (request.getMethod().equalsIgnoreCase("get"))
            objectMap = ParamUtils.getInstance().getParam2Get(request);
        else
            objectMap = ParamUtils.getInstance().json2Map(ParamUtils.getInstance().get());


        if (objectMap != null && !objectMap.isEmpty()) {
            Object o = null;

            if (s == null) {
                o = objectMap.get(SecurityFieldEnum.TOKEN.getName());
                if (o == null)
                    throw new NoParamsException(String.format("參數%s不存在", SecurityFieldEnum.TOKEN.getName()));

                if (!checkToken(request, (String) o)) {
                    throw new TokenException(String.format("%s已過時,請從新登陸", SecurityFieldEnum.TOKEN.getName()));
                }
            }

            o = objectMap.get(SecurityFieldEnum.TIMESTAMP.getName());
            if (o == null)
                throw new NoParamsException(String.format("參數%s不存在", SecurityFieldEnum.TIMESTAMP.getName()));

            Long timestamp = StringUtil.toLong(o);

            if (LocalDateUtils.nowTime().getTime() - timestamp >= 60 * 1000)
                throw new NoParamsException(String.format("參數%s已過時", SecurityFieldEnum.TIMESTAMP.getName()));


            o = objectMap.get(SecurityFieldEnum.CLIENT.getName());
            if (o == null || SecurityFieldEnum.APP.getName().equals((String) o)) {  //這裏獲取CLIENT是爲了防止有些項目沒法進行sign驗證, 也能夠去掉該驗證
                o = objectMap.get(SecurityFieldEnum.SIGN.getName());
                if (o == null)
                    throw new NoParamsException(String.format("參數%s不存在", SecurityFieldEnum.SIGN.getName()));

                String sign = (String) o;

                String paramsSign = ParamUtils.getInstance().getSign(objectMap);
                if (!sign.equals(paramsSign)) {
                    throw new NoParamsException(String.format("參數%s驗證不正確", SecurityFieldEnum.SIGN.getName()));
                }

            }
            return true;
        }
    }
    return false;
  }

  public abstract boolean checkToken(HttpServletRequest request, String token);
  public abstract boolean checkIp(HttpServletRequest request, String ip);

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

  }
}

複製代碼

這一大串的判斷, 誰來給我優化下啊 -_-~~

錯誤信息引導

在攔截器中咱們throw了一些異常, 在這裏咱們須要包裝錯誤返回給用戶

這裏使用@ControllerAdvice配合@ExceptionHandler來實現

ExceptionAspect

@ControllerAdvice
@ResponseBody
public class ExceptionAspect {

  /**
    * 500 - Token is invaild
    */
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  @ExceptionHandler(TokenException.class)
  public Response handleTokenException(TokenException e) {
      e.printStackTrace();
      return new Response().failure(e.getMsg(), ResultCode.NO_TOKEN);
  }

  /***
    * 參數有誤
    */
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  @ExceptionHandler(NoParamsException.class)
  public Response handleTokenException(NoParamsException e) {
      e.printStackTrace();
      return new Response().failure(e.getMsg(), ResultCode.PARAM_ERROR);
  }
}

複製代碼

結合個人小說項目運行 查看效果

正式編碼已經完成 咱們來看下效果

配置

maven引入

<dependency>
    <groupId>com.sanq.product.x_utils</groupId>
    <artifactId>util_security</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
複製代碼

web.xml配置

<filter>
    <filter-name>securityFilter</filter-name>
    <filter-class>com.sanq.product.security.filters.SecurityFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>securityFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
複製代碼

spring-mvc.xml配置

// 加載掃描錯誤信息的包
<context:component-scan base-package="com.sanq.product.books.controller, com.sanq.product.redis.service.impl.single, com.sanq.product.security.aspect" />

//配置攔截器
<mvc:interceptors>
    <bean class="com.sanq.product.books.interceptors.SecurityInterceptor" />
</mvc:interceptors>

複製代碼

SecurityInterceptor

public class SecurityInterceptor extends com.sanq.product.security.interceptors.SecurityInterceptor {

  @Resource
  private JedisPoolService jedisPoolService;
  private static final int MAX = 60; 

  @Override
  public boolean checkToken(HttpServletRequest request, String token) {
      return jedisPoolService.exists(Redis.ReplaceKey.getTokenUser(token));
  }

  @Override
  public boolean checkIp(HttpServletRequest request, String ip) {
      //統計ip訪問次數的key
      String ipKey = Redis.ReplaceKey.getCheckIpKey(ip);

      //BLOCK_IP_SET: 黑名單的key
      if (jedisPoolService.zrank(Redis.RedisKey.BLOCK_IP_SET, ip)) {
        LogUtil.getInstance(SecurityInterceptor.class).i("ip進入了黑名單");
        return true;
      }

      String ipCountTmp = jedisPoolService.get(ipKey);
      int ipCount = StringUtil.toInteger(ipCountTmp != null ? ipCountTmp : 0);

      if (ipCount > MAX) {
          jedisPoolService.putSet(Redis.RedisKey.BLOCK_IP_SET, 1, ip);
          jedisPoolService.delete(ipKey);
          return true;
      }

      jedisPoolService.incrAtTime(ipKey, MAX);

      return false;
  }
}
複製代碼

完結

到此咱們關於接口安全的攔截就已經所有實現完成。 也歡迎大膽的嘗試更改。

但願你們均可以寫出更加優雅,健壯的程序

擴展

關於js端MD5的加密, 你們可使用js-md5, 親測和後端加密後獲得的數據是一直的

md5("引入js,調用md5()方法");
複製代碼
相關文章
相關標籤/搜索