API接口防止参数篡改和重放攻击( 二 )

配置拦截器@Autowiredprivate RedisTemplate<String, String> redisTemplate;@Value("${security.api.key}")private String key;registry.addInterceptor(new SignAuthInterceptor(redisTemplate, key)).addPathPatterns("/live-text/check/**")Postman接口测试

借助Postman的Pre-request Scritp可以实现自动签名功能,每次请求都会生成一个新的签名
使用Pre-request Script脚本实现签名功能
API接口防止参数篡改和重放攻击

文章插图
 
输入Pre-request Script,请复制粘贴下面提供的JAVA Script代码到文本框当中
//设置当前时间戳(毫秒)var timestamp =Math.round(new Date()/1000);pm.globals.set("timestamp",timestamp);var nonceStr = createUuid();pm.globals.set("nonceStr",nonceStr);var key =pm.environment.get("key"); console.log(key);var qs = urlToSign();qs += '×tamp='+timestamp+'&nonceStr='+nonceStr+'&key='+key;console.log(qs);var signature = CryptoJS.MD5(qs).toString();console.log(signature);pm.environment.set("signature", signature);function urlToSign() {var params = new Map();var contentType = request.headers["content-type"];if (contentType && contentType.startsWith('application/x-www-form-urlencoded')) {const formParams = request.data.split("&");formParams.forEach((p) => {const ss = p.split('=');params.set(ss[0], ss[1]);})}const ss = request.url.split('?');if (ss.length > 1 && ss[1]) {const queryParams = ss[1].split('&');queryParams.forEach((p) => {const ss = p.split('=');params.set(ss[0], ss[1]);})}var sortedKeys = Array.from(params.keys())sortedKeys.sort();var l1 = ss[0].lastIndexOf('/');var first = true;var qsfor (var k of sortedKeys) {var s = k + "=" + params.get(k);qs = qs ? qs + "&" + s : s;console.log("key=" + k + " value=https://www.isolves.com/it/cxkf/bk/2020-05-13/" + params.get(k));}return qs;}function createUuid() {return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);return v.toString(16);});}设置环境变量/全局变量
API接口防止参数篡改和重放攻击

文章插图
 
对中文参数进行转码选中需要进行转码的参数,然后点击鼠标右键选中 EncodeURLComponent
API接口防止参数篡改和重放攻击

文章插图
 




推荐阅读