背景:短信接口有調用限制,若是受到惡意攻擊,很容易就爆掉,因此須要一系列驗證機制,後端採用簽名加密的方式,而前端要作人機識別,有兩個要求:html
1)不能使用文本式的驗證碼,很簡單就能拿到前端
2)全部驗證邏輯要在服務端進行,否則很容易被繞過node
解決方法:使用svg-captcha插件在node.js中生成svg格式的驗證碼。git
一、安裝github
npm install --save svg-captcha
二、使用方法ajax
var svgCaptcha = require('svg-captcha'); var data = svgCaptcha.create({ //options }) console.log(data) //{data: '<svg>......</svg>', text: 'fdsafasdf'}
在express中使用express
var svgCaptcha = require('svg-captcha'); var router = require('express').Router(); router.get('/get-img-verify', function (req, res) { console.log(req.query); var option = req.query; // 驗證碼,有兩個屬性,text是字符,data是svg代碼 var code = svgCaptcha.create(option); // 保存到session,忽略大小寫 req.session["randomcode"] = code.text.toLowerCase(); // 返回數據直接放入頁面元素展現便可 res.send({ img: code.data }); });
客戶端獲取驗證碼npm
/* * 獲取圖片驗證碼 */ getImageCode: function () { var _this = this; $("#image_code").val(""); $.ajax({ type:"get", url: "/get-img-verify", data: { size: 6, //驗證碼長度 width: 200, height: 150, background: "#f4f3f2",//干擾線條數 noise: 2, fontSize: 32, ignoreChars: '0o1i', //驗證碼字符中排除'0o1i' color: true // 驗證碼的字符是否有顏色,默認沒有,若是設定了背景,則默認有 }, dataType: 'json' }).done(function (data) { $(".getImageCode").html(data.img); $(".getImageCode").off("click").on("click", function () { _this.getImageCode(); }); }); }
三、驗證方法json
全部的驗證邏輯都要在服務端進行,否則這個驗證碼就沒什麼卵用了,因此正確的邏輯應該是,當去請求敏感接口的時候,把客戶端輸入的驗證碼連同接口須要的參數一塊傳給node層,在node裏判斷用戶輸入的驗證碼是否是跟以前存到session裏的驗證碼一致,若是不一致,則驗證不經過,直接返回數據,不請求後臺;若是一致,則驗證經過,再由node發起請求,去調用後臺接口。後端
router.get('/cerification-codeService/send-verification-code', function (req, res, next) { var url = urlMap.useraccountserver + '/cerification-codeService/new-send-verification-code'; var imageCode = req.query.imageCode.toLowerCase(); var qs = req.query; for (let key in qs) { if (key === 'imageCode') { delete qs[key]; } } if (imageCode !== req.session["randomcode"]) { res.send({ code: 4 }); return false; } var options = { url: url, method: 'GET', json: true, qs: qs }; clusterUtility.API.optionsFilter(req, options); request(options, function (error, response, body) { res.send(body); }); });
插件還有一些其餘的配置項及API,具體可見 https://github.com/lemonce/svg-captcha