因为工作的原因需要使用Google验证码ReCaptcha v3,所以我就上网了解了一下,下面是我的一些学习分享。
大家应该都是用过google的验证码,如
这种情况的需要我们手动去选择,ReCaptcha V3则不需要了,不需要用户去手动的验证。
大白话:用户不用再选择哪些图里有飞机,哪些图里有汽车等。ReCaptcha V3 会在后台对用户的行为进行监测,然后会返回一个分数(0-1)之间,我们就可以自定义了,小于0.5的就是机器人,他们就需要被验证,验证手机号等。
1.首先是去reCaptcha官网网站:https://developers.google.com/recaptcha/
很不幸,这个网站需要翻墙,如果你没有能力,那就算了,因为我不能告诉你怎么翻墙。
标签随便写,这个无所谓
选择第三版
域名可以写自己的域名,也可以用localhost去测试
所有者就是你的google账号了,自己去注册
2.提交之后就会显示两个密钥,一个是客户端的,一个是服务端的
他会提示你怎么去实现,我在这里写我用的实现方法
3.前端页面html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>谷歌ReCaptcha</title>
</head>
<body>
<button>点击我执行验证</button>
<script src="https://www.recaptcha.net/recaptcha/api.js?render=这里写你的客户端密钥"></script>
<script type="text/javascript">
const CAPTCHA_CLIENT_SECRET = "这里也写你的客户端密钥";
window.onload = () => {
document.querySelector('button').addEventListener('click', () => {
grecaptcha.execute(CAPTCHA_CLIENT_SECRET, {action: 'homepage'}).then(function(token) {
console.log('客户端token:' + token);
fetch('/validate?token=' + token, {
method: 'GET'
}).then(response => {
if (response.ok){
response.json().then(message => {
console.log('服务端验证');
console.log(message);
});
}
});
});
});
};
</script>
</body>
</html>
关键的代码
grecaptcha.execute(CAPTCHA_CLIENT_SECRET, {action: 'homepage'}).then(function(token) { //执行请求到google去获得一个taken console.log('客户端token:' + token); fetch('/validate?token=' + token, { //将得到的请求发送到服务端,服务端做相应的处理 method: 'GET' }).then(response => { if (response.ok){ response.json().then(message => { console.log('服务端验证'); console.log(message); }); } }); }
4.后端代码
@RequestMapping("/validate")
@ResponseBody
public String check(HttpServletRequest request) {
String checkCode = request.getParameter("token");
String secret = "6LdTTf8cAAAAAJnW4jipqR0t03pG-84zpPwGPXfQ";
String param = "secret="+secret+"&response="
+ checkCode;
String json = HttpSendUtil.instance().sendPost("https://www.recaptcha.net/recaptcha/api/siteverify", param, "UTF-8");
return json;
}
首先你会发现你没有这个HttpSendUtil,没关系,我有
package com.sendy.boot.controller;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpSendUtil {
private HttpSendUtil() {
}
private static class HttpSendUtilInstance {
private static final HttpSendUtil INSTANCE = new HttpSendUtil();
}
public static HttpSendUtil instance() {
return HttpSendUtilInstance.INSTANCE;
}
public String sendPost(String sendUrl, String params, String encodType) {
StringBuffer receive = new StringBuffer();
HttpURLConnection URLConn = null;
BufferedWriter bw = null;
BufferedReader br = null;
try {
URL url = new URL(sendUrl);
URLConn = (HttpURLConnection) url.openConnection();
URLConn.setRequestMethod("POST");
URLConn.setDoOutput(true);
URLConn.setDoInput(true);
URLConn.setUseCaches(false);
URLConn.setAllowUserInteraction(true);
HttpURLConnection.setFollowRedirects(true);
URLConn.setInstanceFollowRedirects(true);
URLConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
URLConn.setRequestProperty("Content-Length", String.valueOf(params.getBytes().length));
DataOutputStream dos = new DataOutputStream(URLConn.getOutputStream());
dos.writeBytes(params);
br = new BufferedReader(new InputStreamReader(URLConn.getInputStream(), encodType));
String line;
while ((line = br.readLine()) != null) {
receive.append(line).append("\r\n");
}
br.close();
} catch (java.io.IOException e) {
receive.append("访问产生了异常-->").append(e.getMessage());
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException ex) {
bw = null;
ex.printStackTrace();
} finally {
if (URLConn != null) {
URLConn.disconnect();
URLConn = null;
}
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
} finally {
if (URLConn != null) {
URLConn.disconnect();
URLConn = null;
}
}
}
}
return receive.toString();
}
public String sendGet(String sendUrl, String encodType) {
StringBuffer receive = new StringBuffer();
BufferedReader br = null;
HttpURLConnection URLConn = null;
try {
URL url = new URL(sendUrl);
URLConn = (HttpURLConnection) url.openConnection();
URLConn.setDoInput(true);
URLConn.setDoOutput(true);
URLConn.connect();
URLConn.getOutputStream().flush();
br = new BufferedReader(new InputStreamReader(URLConn.getInputStream(), encodType));
String line;
while ((line = br.readLine()) != null) {
receive.append(line).append("\r\n");
}
} catch (IOException e) {
receive.append("访问产生了异常-->").append(e.getMessage());
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (java.io.IOException ex) {
br = null;
ex.printStackTrace();
} finally {
if (URLConn != null) {
URLConn.disconnect();
URLConn = null;
}
}
}
}
return receive.toString();
}
}
上面这个代码直接用就可以
5.返回的数据
- action: "homepage"
- challenge_ts: "2021-10-30T03:11:43Z" //验证的时间
- hostname: "localhost" //请求的地址
- score: 0.9 //验证得到的分数 0-1
- success: true //是否验证成功
我们可以对这个score进行自定义处理,比你得分低于0.5,你就让他进行验证,怎么验证取决于你自己
上面的地址我都是给你们替换过的,为什么要替换? 因为你不能翻墙啊
www.google.com 替换成 www.recaptcha.net
这一步你不需要做,我在上面已经换好了。
拜拜