Google reCaptcha与Postman的测试

huangapple go评论78阅读模式
英文:

Google reCaptcha test with Postman

问题

我正在创建一个后端端点来处理用户登录。登录的一部分是 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 request 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
Body
{
"password": "password",
"username": "richard",
"recaptchaResponse": "sitekey"
}

Result

Response Code : 200
{ "success": false, "error-codes": [ "invalid-input-response" ]}
Invalid captcha

正如您所看到的,对 https://www.google.com/recaptcha/api/siteverify 的调用返回 200,但 success 是 false。

问题

是否可以使用 Postman 测试 reCaptcha?或者 Google 不会验证 Postman 请求?如果是这样的话,我做错了什么?

英文:

I am creating a backend endpoint to handle user login. Part of the login is a Google reCaptcha.

Google reCaptcha与Postman的测试

I am also creating Postman collections to test the backed api's. I have the following:

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

Body

{
"password": "password",
"username": "richard",
"recaptchaResponse": "sitekey"
}

Result

Response Code : 200
{  "success": false,  "error-codes": [    "invalid-input-response"  ]}
Invalid captcha

As you can see, the call to https://www.google.com/recaptcha/api/siteverify returns a 200, but success is false.

Question

Is it possible to test the reCaptcha with Postman? Or will Google not validate a Postman request? If so, what am I doing wrong?

答案1

得分: 3

POST到 https://www.google.com/recaptcha/api/siteverify

设置内容类型标头(Content-Type):`application/x-www-form-urlencoded`

在请求体中,您需要设置密钥和响应键。

响应值必须事先通过表单提交获得,以获取 `$_POST["g-recaptcha-response"];`

成功响应:

{
    "success": true,
    "challenge_ts": "挑战的时间戳",
    "hostname": "您的主机名"
}

有了这个,siteverify将返回检查结果,就像您在进行验证一样
英文:

POST to https://www.google.com/recaptcha/api/siteverify

Set content type header (Content-Type) : application/x-www-form-urlencoded

In your body you have to set the secret and response keys.

The response value must be obtained beforehand via form submit, to get $_POST["g-recaptcha-response"];

Success response :

{
"success": true,
"challenge_ts": "timestamp of challenge",
"hostname": "yourhostname"
}

Having that the siteverify will return the result of the check as if you were doing the verification

答案2

得分: 1

验证码的存在正是为了验证实际用户是否坐在网站前面,而不是某个像是使用Postman发送请求的程序,因此您可能无法通过某个程序来进行验证。

英文:

captchas are exactly there to verify that an actual user is sitting in front of the website, and not some program which is sending some requests like postman ,So you may no be able to verify it using some program.

huangapple
  • 本文由 发表于 2020年8月19日 15:11:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63481760.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定