428 字
2 分钟
接入CloudFlare的人机验证接口

开始
先去 CloudFlare 注册一个账号并且开通拿到 Turnstile 的站点密钥和密钥
前端以vue为例如何使用人机验证
先导入CloudFlare提供的验证接口
onMounted(() => { const script = document.createElement('script'); script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js'; script.async = true; script.onload = () => { loadTurnstile(); }; document.head.appendChild(script);});
function loadTurnstile() { turnstile.render('#example-container', { sitekey: "<你拿到的站点密钥>", callback: function (token) { console.log(`Challenge Success ${token}`); }, });}接下来在你的这个页面任何想验证的地方
<div id="example-container" data-sitekey="<你拿到的站点密钥>"></div>完成以上操作后,你就可以在你的站点看到人机验证码(ps这个页面我随便写的没有调整样式)

但是这样还是不够的,需要后端配合二次验证
后端需要对前端拿到的token进行验证,这里以java为例 如果你使用的是maven,需要导入依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.16</version></dependency><dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.14</version></dependency>接下来创建一个工具类
import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.entity.StringEntity;import org.apache.http.util.EntityUtils;import org.json.JSONObject;/** * @author ATRI <miko217@xnu.edu.cn> */public class TurnstileUtil { private static final String VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"; private static final String SECRET_KEY = "<替换为你的密钥>";
/** * 验证 Turnstile Token 是否有效 * * @param token 用户提交的 Turnstile Token * @return 验证结果,true 表示验证通过,false 表示失败 */ public static boolean validateToken(String token) { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(VERIFY_URL);
JSONObject requestBody = new JSONObject(); requestBody.put("secret", SECRET_KEY); requestBody.put("response", token);
httpPost.setEntity(new StringEntity(requestBody.toString())); httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = httpClient.execute(httpPost); String responseString = EntityUtils.toString(response.getEntity()); JSONObject jsonResponse = new JSONObject(responseString);
return jsonResponse.getBoolean("success"); } catch (Exception e) { e.printStackTrace(); return false; } }}接下来需要在你任何想要认证的地方
if (!TurnstileUtil.validateToken(token)) { //这个token是前端经过验证后拿到的 throw new ServiceException(ResponseType.TURNSTILE_VERIFICATION_FAILED);}接下来已经接入CloudFlare的接口了
接入CloudFlare的人机验证接口
https://blog.zhenxuna.cn/post/5/分享文章
生成精美分享图或复制链接,与更多人分享本文。
继续浏览
最后更新于 ,距今已过 642 天
部分内容可能已过时