我正在创建一个后端端点来处理用户登录。登录部分是Google reCaptcha .
我还在创建 Postman 集合来测试支持的 api。我有以下内容:
AuthenticationResource.java
@POST
@Path("login")
@ApiOperation(value="Login a user with a username and password and return a jwt")
@ApiResponses({
@ApiResponse(code=200, message="Success"),
@ApiResponse(code=404, message="Not Found")
})
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response login(@ApiParam(required = true) UserLoginDTO userLogin, @Context HttpServletRequest request) {
try {
HttpSession session = request.getSession(true);
logger.info("login: "+userLogin.getUsername());
String username = userLogin.getUsername();
String passwordPlainText = userLogin.getPassword();
String clientRemoteAddr = request.getRemoteAddr();
boolean captchaVerified = VerifyRecaptcha.verify(userLogin.getRecaptcha());
if (!captchaVerified) {
logger.severe("Invalid captcha");
return Response.status(Response.Status.BAD_REQUEST).entity("Invalid captcha").build();
}
VerifyRecaptcha.java
public class VerifyRecaptcha {
private static final Logger logger = Logger.getLogger(VerifyRecaptcha.class.getName());
public static final String url = "https://www.google.com/recaptcha/api/siteverify";
public static final String secret = "my-seceret-key";
private final static String USER_AGENT = "Mozilla/5.0";
public static boolean verify(String gRecaptchaResponse) throws IOException {
if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
return false;
}
try{
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String postParams = "secret=" + secret + "&response="
+ gRecaptchaResponse;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
logger.info("\nSending 'POST' request to URL : " + url);
logger.info("Post parameters : " + postParams);
logger.info("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
logger.info(response.toString());
//parse JSON response and return 'success' value
JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
return jsonObject.getBoolean("success");
}catch(Exception e){
logger.warning("invalid recaptcha: "+gRecaptchaResponse+". "+e.getMessage());
e.printStackTrace();
return false;
}
}
}
postman
POST https://localhost:8443/corporateInterface/rest/user/login
正文
{
"password": "password",
"username": "richard",
"recaptchaResponse": "sitekey"
}
结果
Response Code : 200
{ "success": false, "error-codes": [ "invalid-input-response" ]}
Invalid captcha
如您所见,调用https://www.google.com/recaptcha/api/siteverify返回 200,但成功为 false。
问题
是否可以使用 Postman 测试 reCaptcha?或者 Google 不会验证 Postman 请求吗?如果是这样,我做错了什么?
最佳答案
发布至https://www.google.com/recaptcha/api/siteverify
设置内容类型 header (Content-Type):application/x-www-form-urlencoded
在你的 body 中,你必须设置 secret 和响应 key 。
必须事先通过表单提交获取响应值,以获得$_POST["g-recaptcha-response"];
成功响应:
{
"success": true,
"challenge_ts": "timestamp of challenge",
"hostname": "yourhostname"
}
让 siteverify 将返回检查结果,就像您正在进行验证一样
关于java - 使用 Postman 进行 Google reCaptcha 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63481760/