获得响应 token g-recaptcha-response
后,我使用 reCAPTCHA 进行验证,如下所示:
@Service
public class RecaptchaService {
private static class RecaptchaResponse {
@JsonProperty("success")
private boolean success;
@JsonProperty("error-codes")
private Collection<String> errorCodes;
}
@Value("${recaptcha.url}")
private String recaptchaUrl;
@Value("${recaptcha.secret-key}")
private String recaptchaSecretKey;
public boolean isResponseValid(String response) {
RestTemplate restTemplate = new RestTemplate();
Map<String, String> params = new HashMap<String, String>();
params.put("secret", recaptchaSecretKey);
params.put("response", response);
RecaptchaResponse recaptchaResponse = restTemplate.postForEntity( recaptchaUrl, params, RecaptchaResponse.class).getBody();
return recaptchaResponse.success;
}
}
但我总是得到 false
作为 recaptchaResponse.success
和 [missing-input-response, Missing-input-secret]
作为 错误代码
最佳答案
我也遇到了同样的问题,但很容易解决。我将解释修复方法,然后尝试解释问题。
解决此问题的最简单方法是将参数附加到 URL 并为“对象请求”传递 null。我更改了您的代码来演示更改。
@Service
public class RecaptchaService {
private static class RecaptchaResponse {
@JsonProperty("success")
private boolean success;
@JsonProperty("error-codes")
private Collection<String> errorCodes;
}
@Value("${recaptcha.url}")
private String recaptchaUrl;
@Value("${recaptcha.secret-key}")
private String recaptchaSecretKey;
public boolean isResponseValid(String response) {
RestTemplate restTemplate = new RestTemplate();
recaptchaUrl = new StringBuilder()
.append(recaptchaUrl)
.append("?secret=")
.append(recaptchaSecretKey)
.append("&response=")
.append(response)
.toString();
RecaptchaResponse recaptchaResponse = restTemplate.postForEntity(recaptchaUrl, null, RecaptchaResponse.class).getBody();
return recaptchaResponse.success;
}
}
请告诉我这是否适合您。我将参数从 Hashmap 移至 URL 的原因是 RestTemplate 正在将 Hashmap 参数转换为 JSON 格式。 Recaptcha 无法理解 JSON 格式的参数。将参数移动到 URL 既简单又有效。
关于java - reCaptcha 在用 Google 验证时总是返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39689797/