最近項目短信發(fā)送被人刷了,加了驗證碼哩簿,感覺不好用宵蕉,改為滑塊驗證,這里記錄下节榜。
1 下載 sdk 羡玛,解壓放到項目里面。
image
GeetestConfig 代碼:
注意要把這里的id 和key 替換成自己注冊的宗苍。這里用的是官網(wǎng)提供的文檔
import javax.swing.text.StyledEditorKit.BoldAction;
/**
* GeetestWeb配置文件
*
*
*/
public class GeetestConfig {
// 填入自己的captcha_id和private_key
private static final String geetest_id = "002bc30ff1eef93e912f45814945e752";
private static final String geetest_key = "4193a0e3247b82a26f563d595c447b1a";
private static final boolean newfailback = true;
public static final String getGeetest_id() {
return geetest_id;
}
public static final String getGeetest_key() {
return geetest_key;
}
public static final boolean isnewfailback() {
return newfailback;
}
}
StartCaptchaController 加載滑塊代碼:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ganjiangps.wangdaibus.config.geetest.sdk.java.GeetestLib;
/**
* 獲取滑塊 驗證
* @author cjm
*
*/
@Controller
public class StartCaptchaController {
@RequestMapping("/startCaptcha")
public void StartCaptcha(HttpServletRequest request,
HttpServletResponse response) throws IOException{
GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(),true);
String resStr = "{}";
// 自定義userid
String userid = "test";
//自定義參數(shù),可選擇添加
HashMap<String, String> param = new HashMap<String, String>();
param.put("user_id", userid); //網(wǎng)站用戶id
//param.put("client_type", "web"); //web:電腦上的瀏覽器稼稿;h5:手機上的瀏覽器薄榛,包括移動應(yīng)用內(nèi)完全內(nèi)置的web_view;native:通過原生SDK植入APP應(yīng)用的方式
//param.put("ip_address", "127.0.0.1"); //傳輸用戶請求驗證時所攜帶的IP
// 進行驗證預(yù)處理
int gtServerStatus = gtSdk.preProcess(param);
// 將服務(wù)器狀態(tài)設(shè)置到session中
request.getSession().setAttribute(gtSdk.gtServerStatusSessionKey, gtServerStatus);
// 將userid設(shè)置到session中
request.getSession().setAttribute("geetuserid", userid);
resStr = gtSdk.getResponseStr();
PrintWriter out = response.getWriter();
out.println(resStr);
}
}
VerifyLoginController 驗證代碼:
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ganjiangps.wangdaibus.config.geetest.sdk.java.GeetestLib;
/**
* 驗證測試 Controller
* @author admin
*
*/
@Controller
public class VerifyLoginController {
@ResponseBody
@RequestMapping("/verifyLogin")
public Map<String,String> verifyLogin(HttpServletRequest request,
HttpServletResponse response){
GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(),
GeetestConfig.isnewfailback());
String challenge = request.getParameter(GeetestLib.fn_geetest_challenge);
String validate = request.getParameter(GeetestLib.fn_geetest_validate);
String seccode = request.getParameter(GeetestLib.fn_geetest_seccode);
//從session中獲取gt-server狀態(tài)
int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
//從session中獲取userid
String userid = (String)request.getSession().getAttribute("geetuserid");
//自定義參數(shù),可選擇添加
HashMap<String, String> param = new HashMap<String, String>();
param.put("user_id", userid); //網(wǎng)站用戶id
//param.put("client_type", "web"); //web:電腦上的瀏覽器让歼;h5:手機上的瀏覽器敞恋,包括移動應(yīng)用內(nèi)完全內(nèi)置的web_view;native:通過原生SDK植入APP應(yīng)用的方式
//param.put("ip_address", "127.0.0.1"); //傳輸用戶請求驗證時所攜帶的IP
int gtResult = 0;
if (gt_server_status_code == 1) {
//gt-server正常是越,向gt-server進行二次驗證
gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, param);
System.out.println(gtResult);
} else {
// gt-server非正常情況下耳舅,進行failback模式驗證
System.out.println("failback:use your own server captcha validate");
gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
System.out.println(gtResult);
}
Map<String,String> data = new HashMap<>();
if (gtResult == 1) {
// 驗證成功
data.put("status", "success");
data.put("version", gtSdk.getVersionInfo());
} else {
// 驗證失敗
data.put("status", "fail");
data.put("version", gtSdk.getVersionInfo());
}
return data;
}
}
jsp 測試代碼:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() "://"
request.getServerName() ":" request.getServerPort()
path "/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>gt-node-sdk-demo</title>
<style>
body {
margin: 50px 0;
text-align: center;
font-family: "PingFangSC-Regular", "Open Sans", Arial, "Hiragino Sans GB", "Microsoft YaHei", "STHeiti", "WenQuanYi Micro Hei", SimSun, sans-serif;
}
.inp {
border: 1px solid #cccccc;
border-radius: 2px;
padding: 0 10px;
width: 278px;
height: 40px;
font-size: 18px;
}
.btn {
border: 1px solid #cccccc;
border-radius: 2px;
width: 100px;
height: 40px;
font-size: 16px;
color: #666;
cursor: pointer;
background: white linear-gradient(180deg, #ffffff 0%, #f3f3f3 100%);
}
.btn:hover {
background: white linear-gradient(0deg, #ffffff 0%, #f3f3f3 100%)
}
#captcha1,
#captcha2 {
width: 300px;
display: inline-block;
}
.show {
display: block;
}
.hide {
display: none;
}
#notice1,
#notice2 {
color: red;
}
label {
vertical-align: top;
display: inline-block;
width: 80px;
text-align: right;
}
#wait1, #wait2 {
text-align: left;
color: #666;
margin: 0;
}
</style>
</head>
<body>
<h1>極驗驗證SDKDemo</h1>
<hr>
<form action="gt/ajax-validate1" method="post">
<h2>大圖點擊Demo,使用表單進行二次驗證</h2>
<br>
<div>
<label for="username1">用戶名:</label>
<input class="inp" id="username1" type="text" value="極驗驗證">
</div>
<br>
<div>
<label for="password1">密碼:</label>
<input class="inp" id="password1" type="password" value="123456">
</div>
<br>
<div>
<label>完成驗證:</label>
<div id="captcha1">
<p id="wait1" class="show">正在加載驗證碼......</p>
</div>
</div>
<br>
<p id="notice1" class="hide">請先完成驗證</p>
<input class="btn" id="submit1" type="submit" value="提交">
</form>
<!-- 注意倚评,驗證碼本身是不需要 jquery 庫浦徊,此處使用 jquery 僅為了在 demo 使用,減少代碼量 -->
<script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.js"></script>
<!-- 引入 gt.js天梧,既可以使用其中提供的 initGeetest 初始化函數(shù) -->
<script src="./static/js/geettest/gt.js"></script>
<script>
var handler1 = function (captchaObj) {
$("#submit1").click(function (e) {
var result = captchaObj.getValidate();
if (!result) {
$("#notice1").show();
setTimeout(function () {
$("#notice1").hide();
}, 2000);
e.preventDefault();
}
});
// 將驗證碼加到id為captcha的元素里盔性,同時會有三個input的值用于表單提交
captchaObj.appendTo("#captcha1");
captchaObj.onReady(function () {
$("#wait1").hide();
});
// 更多接口參考:http://www.geetest.com/install/sections/idx-client-sdk.html
};
$.ajax({
url: "/startCaptcha?t=" (new Date()).getTime(), // 加隨機數(shù)防止緩存
type: "get",
dataType: "json",
success: function (data) {
// 調(diào)用 initGeetest 初始化參數(shù)
// 參數(shù)1:配置參數(shù)
// 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象呢岗,之后可以使用它調(diào)用相應(yīng)的接口
initGeetest({
gt: data.gt,
challenge: data.challenge,
new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機
offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機冕香,一般不需要關(guān)注
product: "popup", // 產(chǎn)品形式,包括:float后豫,popup
width: "100%"
// 更多配置參數(shù)請參見:http://www.geetest.com/install/sections/idx-client-sdk.html#config
}, handler1);
}
});
</script>
<br><br>
<hr>
<form>
<h2>滑動demo悉尾,使用ajax進行二次驗證</h2>
<br>
<div>
<label for="username2">用戶名:</label>
<input class="inp" id="username2" type="text" value="極驗驗證">
</div>
<br>
<div>
<label for="password2">密碼:</label>
<input class="inp" id="password2" type="password" value="123456">
</div>
<br>
<div>
<label>完成驗證:</label>
<div id="captcha2">
<p id="wait2" class="show">正在加載驗證碼......</p>
</div>
</div>
<br>
<p id="notice2" class="hide">請先完成驗證</p>
<input class="btn" id="submit2" type="submit" value="提交">
</form>
<script>
var handler2 = function (captchaObj) {
$("#submit2").click(function (e) {
var result = captchaObj.getValidate();
if (!result) {
$("#notice2").show();
setTimeout(function () {
$("#notice2").hide();
}, 2000);
} else {
$.ajax({
url: 'gt/ajax-validate2',
type: 'POST',
dataType: 'json',
data: {
username: $('#username2').val(),
password: $('#password2').val(),
geetest_challenge: result.geetest_challenge,
geetest_validate: result.geetest_validate,
geetest_seccode: result.geetest_seccode
},
success: function (data) {
if (data.status === 'success') {
alert('登錄成功');
} else if (data.status === 'fail') {
alert('登錄失敗');
}
}
})
}
e.preventDefault();
});
// 將驗證碼加到id為captcha的元素里,同時會有三個input的值用于表單提交
captchaObj.appendTo("#captcha2");
captchaObj.onReady(function () {
$("#wait2").hide();
});
// 更多接口參考:http://www.geetest.com/install/sections/idx-client-sdk.html
};
$.ajax({
url: "/startCaptcha?t=" (new Date()).getTime(), // 加隨機數(shù)防止緩存
type: "get",
dataType: "json",
success: function (data) {
// 調(diào)用 initGeetest 初始化參數(shù)
// 參數(shù)1:配置參數(shù)
// 參數(shù)2:回調(diào)挫酿,回調(diào)的第一個參數(shù)驗證碼對象构眯,之后可以使用它調(diào)用相應(yīng)的接口
initGeetest({
gt: data.gt,
challenge: data.challenge,
new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機
offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機,一般不需要關(guān)注
product: "popup", // 產(chǎn)品形式早龟,包括:float惫霸,popup
width: "100%"
// 更多配置參數(shù)請參見:http://www.geetest.com/install/sections/idx-client-sdk.html#config
}, handler2);
}
});
</script>
</body>
</html>
瀏覽器效果如圖:
image