Cloudflare人机验证是一种通过验证用户是否为真实用户而不是自动机器人的方法。它旨在保护网站免受恶意机器人的攻击,以确保只有真实用户能够访问网站。

添加Turnstile站点

登录https://dash.cloudflare.com/,在侧边栏点击Turnstile,点击添加站点

2024-02-08T22:15:53.576855446-outf.png填入表单点击创建

2024-02-08T22:19:16.972627864-klif.png

获取到站点秘钥和秘钥。

2024-02-08T22:20:19.944976167-kycg.png

前端实例代码

<!DOCTYPE html>
<html lang="en">
<head>
	<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?onload=_turnstileCb" async defer></script>+
        <script type="text/javascript" src="./assets/js/jquery-2.1.1.min.js"></script>
</head>
<body>
<input type="hidden" id="cloudflare-token">
<div id="myWidget"></div>
</body>
<script>
function login(){
	var token  = $('#cloudflare-token').val();
	if(token.length == 0){
		alert('人机检测失败');
		return false;
	}
 
	$.ajax ({
		url : '/login' ,
		cache: false,
		type: 'POST',
		data:{
			cloudflaretoken: token
		},
		error: function(xhr){
			alert("ajax error");
		},
		success: function(response){
			...
		}
	});
}
 
function _turnstileCb() {
	console.debug('_turnstileCb called');
 
	turnstile.render('#myWidget', {
		sitekey: '站点秘钥',
		theme: 'auto',
		callback: function(token) {
                        console.log(`Challenge Success ${token}`);
			$('#cloudflare-token').val(token);
                },
	});
}
</script>
</html>

后端实例java代码

Controller

public class LoginController {

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public JsonUtil login(HttpServletResponse response, HttpServletRequest request) throws URISyntaxException {

        String cloudflaretoken = request.getParameter("cloudflaretoken");、

        Map params = Maps.newHashMap();
        params.put("secret", "秘钥");
        params.put("response", cloudflaretoken);

        String result = cloudflareService.cloudflareToken(new URI("https://challenges.cloudflare.com"), params);

        JSONObject resultparse = JSONObject.parseObject(result);
        String resultsuccess = resultparse.getString("success");

        if ("false".equals(resultsuccess)) {
            return new JsonUtil(-1, "人机检测失败", false, null);
        }
        
        return new JsonUtil(1, "login success", true, null);
    }

Service

@FeignClient(name="FeignClient", url = "EMPTY")
public interface cloudflareService {
    @PostMapping(value = "/turnstile/v0/siteverify" , consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    String cloudflareToken(URI uri, Map params);
}

注:代码做了精简,需要自己做补充。

参考文档

https://developers.cloudflare.com/turnstile/