스프링

 

 


1.  Google reCAPTCHA 사이트에 들어가 admin console 사이트를 등록  및 키값 가져오기

 

https://www.google.com/recaptcha/about/
 

 

 

2. 라이브러리 등록

 

	 <!-- 구글 리캡챠 사용하기 위한 json //시작 -->
        <dependency>
            <groupId>net.tanesha.recaptcha4j</groupId>
            <artifactId>recaptcha4j</artifactId>
            <version>0.0.7</version>
        </dependency>
        <dependency>
            <groupId>javax.json</groupId>
            <artifactId>javax.json-api</artifactId>         
        </dependency>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.json</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>        
	   <!-- 구글 리캡챠 사용하기 위한 json  //끝 -->		

 

 

3. ReCaptchaController  컨트롤 생성

import java.io.IOException;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sam.coffeeshop.domain.VerifyRecaptcha;

@Controller
public class ReCaptchaController {

	@ResponseBody
	@PostMapping(value = "VerifyRecaptcha")
	public ResponseEntity<?> VerifyRecaptcha(String recaptcha) throws IOException {
		VerifyRecaptcha.setSecretKey("키값");		
		return ResponseEntity.status(HttpStatus.OK).body(VerifyRecaptcha.verify(recaptcha));
	}

}


 

 

 

4. VerifyRecaptcha.java  생성

package com.sam.coffeeshop.domain;

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

import javax.net.ssl.HttpsURLConnection;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class VerifyRecaptcha {

	public static final String url = "https://www.google.com/recaptcha/api/siteverify";
	private final static String USER_AGENT = "Mozilla/5.0";
	private static String secret = ""; // local

	public static void setSecretKey(String key) {
		secret = key;
	}

	public static Object 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();
			log.info("Post parameters : {} ", postParams);
			log.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();

			return response;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}

 

 

 

 

5.View 

	
<form id="frm1">
<div class="g-recaptcha" data-sitekey="구글사이트에서 사용자에게 제공하는 HTML 코드"></div>
<button type="button" id="qnaRegBtn">등록</button>										
</form>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- 구글 리캡차 -->
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
	
	$(function() {
		$('#qnaRegBtn').click(function() {
		
			
			$.ajax({
				url: '/VerifyRecaptcha',
				type: 'post',
				data: {recaptcha: $("#g-recaptcha-response").val()},
				success: function(res) {
					const data=JSON.parse(res);
					if(data.success){
						//alert("자동 가입 방지 봇 통과");
                                              $("#frm1").submit();
					}else{
						alert("자동 가입 방지 봇을 확인 한뒤 진행 해 주세요.");								
					}				
				}
			});	
			
			
			
		});
		
	});
</script>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

spring

 

about author

PHRASE

Level 60  라이트

여러 사람을 즐겁게 하는 사람은 오래 살며, 제 몸만 즐기는 사람은 망하느니라. -선문보훈집

댓글 ( 4)

댓글 남기기

작성

스프링 목록    more