google-retaptcha测试

m0rkklqb  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(192)

我正在创建一个后端端点来处理用户登录。登录的一部分是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,但success为false。
问题
有没有可能和 Postman 一起测试一下?或者谷歌不会验证 Postman 的请求?如果是,我做错了什么?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题