秒殺接口地址隱藏
每次點擊秒殺按鈕,纔會生成秒殺地址,秒殺地址不是寫死的,是從服務端獲取,動態拼接而成的地址。(HTTP協議是明文傳輸,前端是防不住惡意用戶的攻擊,所以安全校驗要放在服務端,從而禁止掉這些惡意攻擊。)
實現思路:
在進行秒殺之前,去後端獲取一個動態的秒殺地址path(服務端生成隨機數作爲path),在然後將這個隨機數返回給前端,前端用這個path拼接在新的請求url(url : “/miaosha/” + path + “/do_miaosha”)上作爲參數,再去發請求到後臺開始我們的秒殺
1、改造前端秒殺按鈕,在發起請求之前,先去獲取秒殺地址:
<button class="btn btn-primary" type="button" id="buyButton" onclick="getMiaoshaPath()">立即秒殺</button>
2、 發起請求/miaosha/getPath去後端獲取一個動態的秒殺地址path,然後前端在用這個path拼接在url(url : “/miaosha/” + path + “/do_miaosha”)上作爲參數,再去發請求到後臺開始我們的秒殺
getMiaoshaPath和doMiaosha(path)代碼:
//獲取秒殺地址
function getMiaoshaPath() {
var goodsId = $("#goodsId").val();
$.ajax({
url : "/miaosha/getPath",
type : "GET",
data : {
goodsId : goodsId,
//vertifyCode:$("#vertifyCode").val()
},
success : function(data) {
if (data.code == 0) {
//獲取秒殺地址
var path = data.data;
//拿到path之後,纔去做我的秒殺邏輯,並且在方法傳入秒殺地址
doMiaosha(path);
} else {
layer.msg(data.msg);
}
},
error : function() {
layer.msg("請求有誤!");
}
});
}
function doMiaosha(path) {
//alert(path);
$.ajax({
url : "/miaosha/" + path + "/do_miaosha",
type : "POST",
data : {
goodsId : $("#goodsId").val()
},
success : function(data) {
if (data.code == 0) {
getMiaoshaResult($("#goodsId").val());
} else {
layer.msg(data.msg);
}
},
error : function() {
layer.msg("請求有誤!");
}
});
}
3、 服務端生成隨機數作爲path,並且存入緩存(設置緩存過期時間60s),然後將這個隨機數返回給前端
/**
* 獲取秒殺的path,並且驗證驗證碼的值是否正確
*/
@RequestMapping(value ="/getPath")
@ResponseBody
public Result<String> getMiaoshaPath(HttpServletRequest request,Model model,MiaoshaUser user,
@RequestParam("goodsId") Long goodsId,
@RequestParam(value="vertifyCode",defaultValue="0") int vertifyCode) {
model.addAttribute("user", user);
//如果用戶爲空,則返回至登錄頁面
if(user==null){
return Result.error(CodeMsg.SESSION_ERROR);
}
//生成一個隨機串
String path=miaoshaService.createMiaoshaPath(user,goodsId);
return Result.success(path);
}
注意:寫入緩存,是後端接收到這個請求秒殺地址path參數,並且與緩存中的存的path比較,如果一致,進行秒殺邏輯,否則,非法請求
createMiaoshaPath方法:
/**
* 生成一個秒殺path,寫入緩存,並且,返回至前臺
*/
public String createMiaoshaPath(MiaoshaUser user, Long goodsId) {
String str=MD5Util.md5(UUIDUtil.uuid()+"123456");
//將隨機串保存在客戶端,並且返回至客戶端。
//String path=""+user.getId()+"_"+goodsId;
redisService.set(MiaoshaKey.getMiaoshaPath, ""+user.getId()+"_"+goodsId, str);
return str;
}
加上了秒殺接口地址隱藏之後可以防止惡意用戶登陸之後,通過不斷調用秒殺地址接口,騷擾服務器,所以使用動態獲取秒殺地址,只有真正點擊秒殺按鈕,纔會根據用戶id和商品goodsId生成對應的秒殺接口地址。
但是,這種情況仍然不能解決利用機器人頻繁點擊按鈕的操作,爲了降低點擊按鈕的次數,以及高併發下,防止多個用戶在同一時間內,併發出大量請求,加入數學公式圖形驗證碼以及接口防刷等優化技術。