Springboot 集成geetest滑块验证码 全程代码
source link: https://zhuanlan.zhihu.com/p/102940883
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Springboot 集成geetest滑块验证码 全程代码
最近项目短信发送被人刷了,加了验证码,感觉不好用,改为滑块验证,这里记录下。
1 下载 sdk ,解压放到项目里面。
GeetestConfig 代码:
注意要把这里的id 和key 替换成自己注册的。这里用的是官网提供的文档
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";
//自定义参数,可选择添加
HashMap<String, String> param = new HashMap<String, String>();
param.put("user_id", userid); //网站用户id
//param.put("client_type", "web"); //web:电脑上的浏览器;h5:手机上的浏览器,包括移动应用内完全内置的web_view;native:通过原生SDK植入APP应用的方式
//param.put("ip_address", "127.0.0.1"); //传输用户请求验证时所携带的IP
// 进行验证预处理
int gtServerStatus = gtSdk.preProcess(param);
// 将服务器状态设置到session中
request.getSession().setAttribute(gtSdk.gtServerStatusSessionKey, gtServerStatus);
// 将userid设置到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状态
int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
//从session中获取userid
String userid = (String)request.getSession().getAttribute("geetuserid");
//自定义参数,可选择添加
HashMap<String, String> param = new HashMap<String, String>();
param.put("user_id", userid); //网站用户id
//param.put("client_type", "web"); //web:电脑上的浏览器;h5:手机上的浏览器,包括移动应用内完全内置的web_view;native:通过原生SDK植入APP应用的方式
//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 初始化函数 -->
<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(), // 加随机数防止缓存
type: "get",
dataType: "json",
success: function (data) {
// 调用 initGeetest 初始化参数
// 参数1:配置参数
// 参数2:回调,回调的第一个参数验证码对象,之后可以使用它调用相应的接口
initGeetest({
gt: data.gt,
challenge: data.challenge,
new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
offline: !data.success, // 表示用户后台检测极验服务器是否宕机,一般不需要关注
product: "popup", // 产品形式,包括:float,popup
width: "100%"
// 更多配置参数请参见: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(), // 加随机数防止缓存
type: "get",
dataType: "json",
success: function (data) {
// 调用 initGeetest 初始化参数
// 参数1:配置参数
// 参数2:回调,回调的第一个参数验证码对象,之后可以使用它调用相应的接口
initGeetest({
gt: data.gt,
challenge: data.challenge,
new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
offline: !data.success, // 表示用户后台检测极验服务器是否宕机,一般不需要关注
product: "popup", // 产品形式,包括:float,popup
width: "100%"
// 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
}, handler2);
}
});
</script>
</body>
</html>
浏览器效果如图:
想看更多的内容可以看我的主页
Recommend
-
143
PHP+Javascript实现拖动滑块完成拼图验证码
-
39
在爬虫的需求中,越来越多的网站采用验证码来抵御爬虫的入侵,而滑块验证码也被运用在很多的用户登录场景中。 我们若是去分析它的接口规则,往往得不偿失,主要是因为这类接口加密参数多且更新频繁,一旦更...
-
45
Light-Swiper 专注于移动端、轻量级Swiper原生插件(3kb gziped)。触摸事件基于element,不影响页面的触摸事件(如右滑返回上一页) 重构于Swipe,实现自定义swipe宽度、偏移量、无限轮播、事件复制等功能,体验更加流畅
-
6
Apple Watch界面设计规范(16) - UI元素 - 滑块 原文来自苹果官方于2014年11月发布的预备版本Apple Watch界面设计规范。相关信息及目录详见
-
1
【opencv 五】利用 opencv 给读入的视频添加拖动滑块 1年前 ⋅...
-
10
写在前面: 其实本程序还有很多需要完善和改进的地方,后面会进行完善,大家多多包涵 通过完整图片与缺失滑块的图片进行像素对比,确定滑块位置边缘检测算法,确定位置规避检测,模拟人的行为进行滑动滑块
-
3
全程直播个人博客重构过程,采用springboot+dubbo+jpa技术栈。 - 左潇龙 - 博客园 ...
-
4
HarmonyOS 实现一个滑块验证-51CTO.COM HarmonyOS 实现一个滑块验证 作者:lxj29 2022-08-02 14:21:20 本篇文章我来尝试着实现一个滑动验证码。当然,这种验证码一般都是第三方来处...
-
4
#夏日挑战赛# HarmonyOS 实现一个滑块验证 推荐 原创 开源基础软件社区官方
-
4
爬虫怎么破解滑块验证码? - V2EX V2EX › 程序员 爬虫怎么...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK