Spring Boot Gateway 自定义网关, 实现 HmacMD5 鉴权


1. application.yml 文件中添加: 
web-mvc-configurer:
  auths:
    - app_id: test
      key: 123
    - app_id: admin
      key: 35986392d2d94eadadf8558eac9f2771

2. 编写网关控制类
package com.my.app.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 网关
 */
@Configuration
@ConfigurationProperties(prefix = "web-mvc-configurer")
public class WebController implements WebMvcConfigurer {

    public static List<Map<String, String>> auths;

    public static List<Map<String, String>> getAuths() {
        return auths;
    }

    public void setAuths(List<Map<String, String>> auths) {
        WebController.auths = auths;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration registration = registry.addInterceptor(new IHandlerInterceptor());
        registration.addPathPatterns("/open/**");
    }

    public static class IHandlerInterceptor implements HandlerInterceptor {

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

            String app_id = request.getParameter("app_id");
            String key = "";
            if(StringUtils.isBlank(app_id)) {
                printWriter(response, "缺少参数: app_id");
                return false;
            } else if(auths != null && auths.size() > 0) {
                for(Map<String, String> map : auths) {
                    if(app_id.equals(map.get("app_id"))) {
                        key = map.get("key");
                        break;
                    }
                }
            }

            if(StringUtils.isBlank(key)) {
                printWriter(response, "参数无效: key");
                return false;
            }

            String timestamp = request.getParameter("timestamp");
            if(StringUtils.isBlank(timestamp)) {
                printWriter(response, "缺少参数: timestamp");
                return false;
            } else {
                try {
                    LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(timestamp)), ZoneId.systemDefault());
                } catch (Exception e) {
                    e.printStackTrace();
                    printWriter(response, "参数无效: timestamp");
                    return false;
                }
            }

            String version = request.getParameter("version");
            if(StringUtils.isBlank(version)) {
                printWriter(response, "缺少参数: version");
                return false;
            } else if(!version.equals("1.0")) {
                printWriter(response, "非法参数: version");
                return false;
            }

            String sign = request.getParameter("sign");
            if(StringUtils.isBlank(sign)) {
                printWriter(response, "缺少参数: sign");
                return false;
            }

            SortedMap<String, Object> parameters = new TreeMap<>();
            for(String queryString : request.getQueryString().split("&")) {
                parameters.put(queryString.split("=")[0], queryString.split("=")[1]);
            }

            StringBuilder stringBuilder = new StringBuilder();
            for (Map.Entry<String, Object> entry : parameters.entrySet()) {
                if(!entry.getKey().equals("sign")) {
                    stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
            }

            try {
                String hmacMD5 = HmacMD5(key, stringBuilder.substring(0, stringBuilder.toString().length() - 1));
                if(!sign.equals(hmacMD5)) {
                    printWriter(response, "sign 无效");
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                printWriter(response, e.getMessage());
                return false;
            }
            return true;
        }

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

        }

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

        }

        private void printWriter(HttpServletResponse response, String msg) throws IOException {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            PrintWriter writer = response.getWriter();
            JSONObject responseData = new JSONObject();
            responseData.put("msg", msg);
            responseData.put("status", 500);
            responseData.put("succeed", false);
            writer.print(responseData);
        }

        private String HmacMD5(String key, String data) throws NoSuchAlgorithmException, InvalidKeyException {
            SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacMD5");
            Mac mac = Mac.getInstance("HmacMD5");
            mac.init(secretKey);
            byte[] bytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; bytes != null && i < bytes.length; i ++) {
                String s = Integer.toHexString(bytes[i] & 0XFF);
                if (s.length() == 1) {
                    stringBuilder.append('0');
                }
                stringBuilder.append(s);
            }
            return stringBuilder.toString().toLowerCase();
        }
    }
}

3. 访问:http://127.0.0.1:8080/open/get?app_id=test&timestamp=1611366230&version=1.0&sign=27785e2b21c02bab696c3e30e4d038ea
返回:
{

    "msg": "请求成功",
    "succeed": true,
    "status": 200

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值