极验是一个提供验证服务的第三方库,可以有效地防止机器人攻击,提高网站的安全性。Spring Boot整合极验可以使用户在登录、注册等敏感操作上获得更好的保障。
以下是整合极验的步骤:
com.geetest.sdk
gt3-sdk
4.0.7-p3
gt:
captcha:
id: [your_id]
key: [your_key]
@RestController
public class CaptchaController {
@Autowired
private CaptchaService captchaService;
@GetMapping("/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response) {
captchaService.generateCaptcha(request, response);
}
}
@Service
public class CaptchaService {
@Autowired
private GeetestLib geetestLib;
public void generateCaptcha(HttpServletRequest request, HttpServletResponse response) {
String userid = UUID.randomUUID().toString();
int gtServerStatus = geetestLib.preProcess(userid);
request.getSession().setAttribute(GeetestLib.gtServerStatusSessionKey, gtServerStatus);
request.getSession().setAttribute(GeetestLib.useridSessionKey, userid);
JSONObject jsonObject = new JSONObject();
jsonObject.put(GeetestLib.gtServerStatusSessionKey, gtServerStatus);
jsonObject.put(GeetestLib.gtUserIdSessionKey, userid);
response.setContentType("application/json;charset=UTF-8");
try {
response.getWriter().write(jsonObject.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean validateCaptcha(HttpServletRequest request) {
String challenge = request.getParameter(GeetestLib.geetestChallenge);
String validate = request.getParameter(GeetestLib.geetestValidate);
String seccode = request.getParameter(GeetestLib.geetestSeccode);
String userid = (String) request.getSession().getAttribute(GeetestLib.useridSessionKey);
int gtServerStatus = (int) request.getSession().getAttribute(GeetestLib.gtServerStatusSessionKey);
int gtResult = 0;
if (gtServerStatus == 1) {
gtResult = geetestLib.enhencedValidateRequest(challenge, validate, seccode, userid);
} else {
gtResult = geetestLib.failbackValidateRequest(challenge, validate, seccode);
}
return gtResult == 1;
}
}
@PostMapping("/login")
public String login(String username, String password, HttpServletRequest request) {
boolean captchaPassed = captchaService.validateCaptcha(request);
if (captchaPassed) {
// 验证码验证通过
// 进行登录操作
} else {
// 验证码验证失败
}
}
@PostMapping("/register")
public String register(String username, String password, HttpServletRequest request) {
boolean captchaPassed = captchaService.validateCaptcha(request);
if (captchaPassed) {
// 验证码验证通过
// 进行注册操作
} else {
// 验证码验证失败
}
}
通过以上步骤,就可以实现Spring Boot整合极验,为用户提供更好的验证服务。