Spring

reCAPTCHA v2

검정95 2021. 6. 26. 23:05

SpringBoot가 아니라 Spring Legacy project 에서 구글의 reCAPTCHA를 사용하는 법

https://developers.google.com/recaptcha/docs/display

 

reCAPTCHA v2  |  Google Developers

This page explains how to display and customize the reCAPTCHA v2 widget on your webpage. To display the widget, you can either: See Configurations to learn how to customize your widget. For example, you may want to specify the language or theme for the wid

developers.google.com

참조

 

우선 

https://console.cloud.google.com/marketplace/product/google/recaptchaenterprise.googleapis.com?returnUrl=%2Fsecurity%2Frecaptcha%3Fproject%3Dcarrotparm%26folder%3D%26organizationId%3D&project=carrotparm 

 

Google Cloud Platform

There is a temporary block on your account. This happens when Google detects requests from your network that may have been sent by malicious software, a browser plug-in, or script that sends automated requests. Retry in a few minutes.

console.cloud.google.com

이곳에서 나만의 프로젝트를 생성하여

사이트 키와 비밀 키를 발급받는다.

그 다음 애널리틱스로 이동을 누른 후 reCAPTCHA v2 Checkbox를 선택하고

사이트 도메인에 주소를 넣어준다. (연습이기 때문에 localhost로 설정함)

 

그 다음 이클립스에서 Spring Legacy Project를 생성해준다.

 

pom.xml에 dependency를 추가 해준다.

VerifyRecaptcha 클래스 생성 후 내용 추가

package com.mvc.upgrade.recaptcha;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.net.ssl.HttpsURLConnection;

public class VerifyRecaptcha {

	
	public static final String url = "http://www.google.com/recaptcha/api/siteverify";
	private final static String USER_AGENT = "Mozilla/5.0";
	private static String secret = "";
	
	public static void setSecretKey(String key) {
		secret = key;
	}
	
	 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();
	        System.out.println("\nSending 'POST' request to URL : " + url);
	        System.out.println("Post parameters : " + postParams);
	        System.out.println("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
	        System.out.println(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){
	            e.printStackTrace();
	            return false;
	        }
	    }
	
}

 

 

 

views 폴더에 jsp파일 생성 후 내용 추가

<script>
$("#recaptcha-anchor").click(function(){
		var captcha = 1;
		
		$.ajax({
            url: 'VerifyRecaptcha.do',
            type: 'post',
            data: {
                recaptcha: $("#g-recaptcha-response").val()
            },
            success: function(data) {
                switch (data) {
                    case 0:
                        console.log("자동 가입 방지 봇 통과");
                        captcha = 0;
                		break;
                    case 1:
                        alert("자동 가입 방지 봇을 확인 한뒤 진행 해 주세요.");
           				captcha = 1;
                        break;
                    default:
                        alert("자동 가입 방지 봇을 실행 하던 중 오류가 발생 했습니다. [Error bot Code : " + Number(data) + "]");
                    	captcha = 1;
                   		break;
                }
            }
        });
		
		  if(captcha != 0) { 
            	return false;
            } else {
            	return captcha;
            }
		});
</script>

<body>
<div class="g-recaptcha" id="recaptcha"
					data-sitekey="위에 구글 홈페이지에서 얻은 홈 키">
</div>
</body>

 

 

Controller에 내용 추가

 

 

모두 완료 후 view에서 보이는 결과

 

로봇이 아닙니다 옆에 체크박스에서 checked 되었을 때 값을 가져오려고 했지만 실패했다.

 

id = "recaptcha-anchor" 부분의 속성 중 aria-checked 부분이 체크되면 true로 바뀌는 것을 확인 후 

$("#recaptcha").attr("aria-checked") 로 해당 값을 가져오려고 했지만 undefined가 계속 발생하여 해결하지 못했다.