获得响应令牌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]
为error-codes
答案 0 :(得分:1)
我有同样的问题,但它很容易解决。我将解释修复,然后尝试解释问题。
解决此问题的最简单方法是将参数附加到URL并为&#39;对象请求传递空值&#39;。我已更改您的代码以证明更改。
@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非常简单且有效。