若依前后端分离加入签名验证

前端签名验证准备

我使用的是uniapp。

// 先引入js-md5,npm引入模式
npm install js-md5 -D

在main.js中生命签名私钥

export const signature = "jiunihuipojie?"

在你封装的request.js中引入js-md5

import {
    
     signature } from "../main.js"
import Md5 from 'js-md5'

在请求拦截中,添加相关内容到请求头

// 请求拦截
	uni.$u.http.interceptors.request.use((config) => {
    
    
		//当前时间戳
		const timeStamp = new Date().getTime();
		//时间戳封装到请求头中
		config.header.timeStamp = timeStamp;
		//封装签名到请求头中 md5加密  签名秘钥 加@符号 加当前时间戳
		config.header.sign = Md5(`${
    
    signature}@${
    
    timeStamp}`).toUpperCase();
		//区分 微信端和后台管理端
		config.header.type = "wxapp"
		
	    config.data = config.data || {
    
    }
	    return config 
	}, config => {
    
     // 可使用async await 做异步操作
	    return Promise.reject(config)
	})

后端签名验证

放入到拦截器中。

//  基于若依的拦截器位置
package com.ruoyi.framework.interceptor;

直接复制粘贴

package com.ruoyi.framework.interceptor;

import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.time.Instant;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;

/**
 * 防止重复提交拦截器
 *
 * @author ruoyi
 */
@Component
public abstract class RepeatSubmitInterceptor implements HandlerInterceptor
{
    
    
    private String secrt = "jiunihuipojie?";

    private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
    
    
    	//获取请求路径
   		String requestURI = request.getRequestURI();
   		//判断是否是图片的请求,若是图片路径有修改,这也要加判断
        if(requestURI.indexOf("/profile")  ==-1){
    
    
        	//不含 /profile 不是图片资源请求
            String sign = request.getHeader("sign");
            String timeStamp = request.getHeader("timeStamp");
            //获取请求的端
            String type = request.getHeader("type");
            //是微信小程序端的话,就执行验签
            if(type.equals("wxapp")){
    
    
                long currentTimestamp = System.currentTimeMillis();
                int diffSeconds = (int) ((currentTimestamp - Long.valueOf(timeStamp)) / 1000);
                if(diffSeconds > 3){
    
    
                    return false;
                }
                String md5Str = secrt + "@" + timeStamp;
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(md5Str.getBytes());
                byte[] digest = md.digest();
                String md5String = bytesToHex(digest);
                if(!md5String.equals(sign)){
    
    
                    return false;
                }
            }
        }
        if (handler instanceof HandlerMethod)
        {
    
    
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            if (annotation != null)
            {
    
    
                if (this.isRepeatSubmit(request, annotation))
                {
    
    
                    AjaxResult ajaxResult = AjaxResult.error(annotation.message());
                    ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
                    return false;
                }
            }
            return true;
        }
        else
        {
    
    
            return true;
        }
    }

    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     *
     * @param request
     * @return
     * @throws Exception
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation);
		//	 MD5 加密
    public static String bytesToHex(byte[] bytes) {
    
    
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
    
    
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45729937/article/details/130606618