Web前后端笔记-vue封装http请求添加signature及后端(Java)解析并验证

 

首先帖下运行截图:

签名过期情况:

Web前后端笔记-vue封装http请求添加signature及后端(Java)解析并验证_第1张图片

签名错误情况:

Web前后端笔记-vue封装http请求添加signature及后端(Java)解析并验证_第2张图片



这里npm要导入js-md5,并且在main.js中添加

import md5 from 'js-md5'
Vue.prototype.$md5 = md5;

首先来看下前端代码:

import axios from 'axios'

axios.defaults.timeout = 35 * 1000;

/**
 *  Get方法
 * @param {*} url 
 * @param {*} params 
 */
export function fetch(url, params = {}){

    return new Promise((resolve, reject) => {

       params['timestamp'] = new Date().getTime();

       let oriInfo = "";
       for(let key in params){

          oriInfo += params[key] + "$";
       }
       let paraString = oriInfo.substr(0, oriInfo.length - 1);
       
       params['signature'] = this.$md5(paraString);
        axios.get(url, {

            params : params
        }).then(response => {

            resolve(response);
          }).catch(err => {

            reject(err)
          })
    })
}


export function post(url, data = {}){

    return new Promise((resolve, reject) => {

        axios.post(url, data)
        .then(response => {

            resolve(response);
        },
        err => {

             reject(err);
        })
    })
}

这里采用的是vue cli,axios要先npm install下。这里目前只对GET方法进行了处理。

 

在main.js中设置下全局的

import {fetch, post} from './xxx/xxx/http'
Vue.prototype.$httpGet = fetch;
Vue.prototype.$httpPost = post;

调用的时候使用这种方式就可以了

this.$httpGet('/xxx/xxx/xxx, {
  'tableName' : 'xxxxx'
  }).then((res)=> {
     //console.log(res);
  });

这里调用httpGet后会将头的数据生成xxx$xxx$xxx生成对应的dm5。

 

这里后端创建一个配置类,extends WebMvcConfigurerAdapter。

这里我用的是1.5.21,2.xx.xx版本用其他类

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {


    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){

        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {

                registry.addInterceptor(new XInterceptor()).addPathPatterns("/xxx/**");
            }
        };

        return adapter;
    }
}

对应的XInterceptor如下:

public class XInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {


        if(httpServletRequest.getMethod().equals("GET")){

            String url = httpServletRequest.getRequestURI();
            String contextPath = httpServletRequest.getServletPath();
            String para = httpServletRequest.getQueryString();
            Enumeration parameterNames = httpServletRequest.getParameterNames();
            Map parameterMap = httpServletRequest.getParameterMap();

            //参数是否正常
            if(!parameterMap.containsKey("timestamp") || !parameterMap.containsKey("signature")){

                httpServletResponse.sendError(503);
                return false;
            }

            //先检测签名是否过期 30s内不会过期
            Long timestamp = Long.valueOf(parameterMap.get("timestamp")[0]);
            Long currentStamp = System.currentTimeMillis();


            if(timestamp < (currentStamp - 30 * 1000)){

                httpServletResponse.sendError(501);
                return false;
            }



            //检查签名是否合法
            String originStr = "";
            for(Enumeration key = parameterNames ; parameterNames.hasMoreElements();){

                String KeyPara = key.nextElement().toString();
                if(KeyPara.equals("signature"))
                    continue;

                originStr += parameterMap.get(KeyPara)[0] + "$";
            }
            originStr = originStr.substring(0, originStr.length() - 1);
            String md5Str = MD5Utils.generateMD5(originStr);
            if(!md5Str.equals(parameterMap.get("signature")[0])){

                httpServletResponse.sendError(502);
                return false;
            }
        }
        else{


        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

这里每一个timestamp生存时间为30s。

 

这里调用httpServletResponse.sendError会被、

@RestController
public class ErrorController implements org.springframework.boot.autoconfigure.web.ErrorController {
    
	@RequestMapping("/error")
	public Object handleError(HttpServletRequest request){
		...
		...
		...
	}
}

会集中到error中处理

你可能感兴趣的:(Spring,Boot,Java,工作笔记,Vue,Spring,Boot,Java)