xiejun
2024-11-01 80b6cbfc9c861469146318d0b3dd5f8b8b525b8a
Source/BladeX-Tool/blade-core-secure/src/main/java/org/springblade/core/secure/interceptor/SignInterceptor.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,170 @@
/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill åº„骞 (smallchill@163.com)
 */
package org.springblade.core.secure.interceptor;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.secure.props.SignSecure;
import org.springblade.core.secure.provider.HttpMethod;
import org.springblade.core.secure.provider.ResponseProvider;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.WebUtil;
import org.springframework.lang.NonNull;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Date;
import java.util.List;
/**
 * ç­¾åè®¤è¯æ‹¦æˆªå™¨æ ¡éªŒ
 *
 * @author Chill
 */
@Slf4j
@AllArgsConstructor
public class SignInterceptor extends HandlerInterceptorAdapter {
   /**
    * è¡¨è¾¾å¼åŒ¹é…
    */
   private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
   /**
    * æŽˆæƒé›†åˆ
    */
   private final List<SignSecure> signSecures;
   /**
    * è¯·æ±‚æ—¶é—´
    */
   private final static String TIMESTAMP = "timestamp";
   /**
    * éšæœºæ•°
    */
   private final static String NONCE = "nonce";
   /**
    * æ—¶é—´éšæœºæ•°ç»„合加密串
    */
   private final static String SIGNATURE = "signature";
   /**
    * sha1加密方式
    */
   private final static String SHA1 = "sha1";
   /**
    * md5加密方式
    */
   private final static String MD5 = "md5";
   /**
    * æ—¶é—´å·®æœ€å°å€¼
    */
   private final static Integer SECOND_MIN = 0;
   /**
    * æ—¶é—´å·®æœ€å¤§å€¼
    */
   private final static Integer SECOND_MAX = 10;
   @Override
   public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
      boolean check = signSecures.stream().filter(signSecure -> checkAuth(request, signSecure)).findFirst().map(
         authSecure -> checkSign(authSecure.getCrypto())
      ).orElse(Boolean.TRUE);
      if (!check) {
         log.warn("授权认证失败,请求接口:{},请求IP:{},请求参数:{}", request.getRequestURI(), WebUtil.getIP(request), JsonUtil.toJson(request.getParameterMap()));
         ResponseProvider.write(response);
         return false;
      }
      return true;
   }
   /**
    * æ£€æµ‹æŽˆæƒ
    */
   private boolean checkAuth(HttpServletRequest request, SignSecure signSecure) {
      return checkMethod(request, signSecure.getMethod()) && checkPath(request, signSecure.getPattern());
   }
   /**
    * æ£€æµ‹è¯·æ±‚方法
    */
   private boolean checkMethod(HttpServletRequest request, HttpMethod method) {
      return method == HttpMethod.ALL || (
         method != null && method == HttpMethod.of(request.getMethod())
      );
   }
   /**
    * æ£€æµ‹è·¯å¾„匹配
    */
   private boolean checkPath(HttpServletRequest request, String pattern) {
      String servletPath = request.getServletPath();
      String pathInfo = request.getPathInfo();
      if (pathInfo != null && pathInfo.length() > 0) {
         servletPath = servletPath + pathInfo;
      }
      return ANT_PATH_MATCHER.match(pattern, servletPath);
   }
   /**
    * æ£€æµ‹è¡¨è¾¾å¼
    */
   private boolean checkSign(String crypto) {
      try {
         HttpServletRequest request = WebUtil.getRequest();
         if (request == null) {
            return false;
         }
         // èŽ·å–å¤´éƒ¨åŠ¨æ€ç­¾åä¿¡æ¯
         String timestamp = request.getHeader(TIMESTAMP);
         // åˆ¤æ–­æ˜¯å¦åœ¨åˆæ³•时间段
         long seconds = Duration.between(new Date(Func.toLong(timestamp)).toInstant(), DateUtil.now().toInstant()).getSeconds();
         if (seconds < SECOND_MIN || seconds > SECOND_MAX) {
            log.warn("授权认证失败,错误信息:{}", "请求时间戳非法");
            return false;
         }
         String nonce = request.getHeader(NONCE);
         String signature = request.getHeader(SIGNATURE);
         // åŠ å¯†ç­¾åæ¯”å¯¹ï¼Œå¯è‡ªè¡Œæ‹“å±•åŠ å¯†è§„åˆ™
         String sign;
         if (crypto.equals(MD5)) {
            sign = DigestUtil.md5Hex(timestamp + nonce);
         } else if (crypto.equals(SHA1)) {
            sign = DigestUtil.sha1Hex(timestamp + nonce);
         } else {
            sign = DigestUtil.sha1Hex(timestamp + nonce);
         }
         return sign.equalsIgnoreCase(signature);
      } catch (Exception e) {
         log.warn("授权认证失败,错误信息:{}", e.getMessage());
         return false;
      }
   }
}