防水墙申请:https://007.qq.com/
前端:
<form id="login" th:action="@{/admin/login}" th:method="post" >
<div>
<label>账号</label>
<input type="text" id="username" name="username"/>
</div>
<div>
<label>密码</label>
<input type="password" id="password" name="password"/>
</div>
<br>
</form>
<!--点击此元素会自动激活验证码-->
<!--id : 元素的id(必须)-->
<!--data-appid : AppID(必须)-->
<!--data-cbfn : 回调函数名(必须)-->
<!--data-biz-state : 业务自定义透传参数(可选)-->
<div id="control" style="text-align: center;margin-top: 10px;">
<button id="TencentCaptcha" onclick="subForm()">点击验证并登录系统</button>
</div>
function subForm(){
var checkUserName = document.getElementById("username").value;
var checkPassword = document.getElementById("password").value;
if(checkUserName == ''){
alert("请先输入用户名!");
}else if(checkPassword == ''){
alert("请输入密码!")
}else{
var captcha1 = new TencentCaptcha('填入appid', function(res) {
if(res.ret === 0){
$.ajax({
type: "POST",
url: "/admin/check",
data: {
"ticket":res.ticket,
"randstr":res.randstr
},
success: function (data) {
if (data ===1) {
into();//验证成功,登录验证
}else{
alert("验证失败,请重新验证!");
}
}
})
}else if(res.ret===2){
alert("验证已关闭,验证成功才能登录系统!");
}
});
captcha1.show();
}
}
function into() {
$('#login').submit();//提交登录表单
}
controller:
@PostMapping("/admin/check")
@ResponseBody
public int check(@RequestParam("ticket") String ticket,
@RequestParam("randstr") String randstr){
//防水墙验证
return TCaptchaVerify.verifyTicket(ticket,randstr);
}
实现类:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.net.URLEncoder;
/**
* 防水墙
*/
public class TCaptchaVerify {
private static final String APP_ID = "填充";
private static final String APP_SECRET = "填充";
private static final String VERIFY_URI = "https://ssl.captcha.qq.com/ticket/verify?aid=%s&AppSecretKey=%s&Ticket=%s&Randstr=%s";
public static int verifyTicket(String ticket, String rand/*, String userIp*/) {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet;
CloseableHttpResponse response = null;
try {
httpGet = new HttpGet(String.format(VERIFY_URI,
APP_ID,
APP_SECRET,
URLEncoder.encode(ticket, "UTF-8"),
URLEncoder.encode(rand, "UTF-8")
/*URLEncoder.encode(userIp, "UTF-8")*/
));
response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String res = EntityUtils.toString(entity);
System.out.println(res); // 临时输出
JSONObject result = JSON.parseObject(res);
// 返回码
int code = result.getInteger("response");
// 恶意等级
int evilLevel = result.getInteger("evil_level");
return code;
}
} catch (java.io.IOException e) {
// 忽略
} finally {
try {
response.close();
} catch (Exception ignore) {
}
}
return -1;
}
}