帶有Angular和Spring App的Google Recaptcha示例

在這篇文章中,您將學習如何使用Angular和Spring / Java App 實現Google Recaptcha。

  1. 從Google獲取Recaptcha代碼(Key)

  2. Angular - 在登錄/註冊組件中處理Recaptcha代碼

  3. Spring / Java - RecaptchaVerifier實用程序類

  4. Spring / Java - 驗證服務器端代碼中的Recaptcha響應

從Google獲取Recaptcha代碼(密鑰)

轉到Google Recaptcha網站並獲取您網站的代碼。Google recaptcha代碼如下所示:

將代碼放在適當的地方登錄,註冊頁面。在登錄表單中,它的代碼如下所示:

帶有Google Recaptcha的註冊表單看起來如下。該工作示例可以在此註冊頁面上找到。

帶有Angular和Spring App的Google Recaptcha示例

Angular - 在登錄/註冊組件時處理Recaptcha代碼

在登錄/註冊組件中處理代碼,以便除非用戶點擊Google Recaptcha,否則不應允許他們繼續進行。請注意grecaptcha.getResponse()等代碼以及與響應長度有關的檢查。

declare var grecaptcha: any;

@Component({

selector: 'app-singup',

templateUrl: './signup.component.html',

styleUrls: ['./signup.component.css']

})

export class SignupComponent implements OnInit {

errormsg: string;

constructor() {

}

ngOnInit() {

}

onSubmit() {

const response = grecaptcha.getResponse();

if (response.length === 0) {

this.errormsg = 'Recaptcha not verified. Please try again!';

return;

}

//

// Rest of the code goes here

//

}

}

Spring / Java RecaptchaVerifier實用程序類

創建一個RecaptchaVerifier實用程序類,用於驗證在請求消息中到達的驗證碼響應代碼。以下是帶有驗證(字符串響應) API 的示例代碼。請注意下面給出的代碼中的一些內容:

  • Google Recaptcha網址,例如https://www.google.com/recaptcha/api/siteverify

  • 谷歌googleRecaptchaSecretKey是自動裝配的。您可能希望從Google Recaptcha網站獲取RecaptchaSecretKey的值,並將其置於application.properties文件中,並將其作為Configuration bean之一讀取。以下是應用程序文件和配置Bean的示例代碼。

  • Application.properties文件代碼

google.recaptcha.site.key = 6YbGpACUBBBBBJ9pa2Km3vYeVCBV8UHYGic-dbGD

google.recaptcha.secret.key = 6LdWpVEUBBBBBI4xJU7n1MN6tOZablGjnguy123B

  • AppConfig.java代碼

@Configuration

@PropertySource("classpath:application.properties")

public class AppConfig {

@Value("${google.recaptcha.site.key}")

String googleRecaptchaSiteKey;

@Value("${google.recaptcha.secret.key}")

String googleRecaptchaSecretKey;

@Bean

public String googleRecaptchaSiteKey() {

return this.googleRecaptchaSiteKey;

}

@Bean

public String googleRecaptchaSecretKey() {

return this.googleRecaptchaSecretKey;

}

}

  • RestClient使用自動裝配。您可以使用Spring RestTemplate創建一個簡單的RestClient。

import java.net.URI;

import org.json.JSONException;

import org.json.JSONObject;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import com.vf.nimki.rest.RestClient;

@Service

public class RecaptchaVerifier {

final static Logger logger = LoggerFactory.getLogger(RecaptchaVerifier.class);

private String secretKey;

private RestClient restClient;

private static final String RECAPTCHA_URL = "https://www.google.com/recaptcha/api/siteverify";

@Autowired

public RecaptchaVerifier(String googleRecaptchaSecretKey, RestClient springRestClient) {

this.secretKey = googleRecaptchaSecretKey;

this.restClient = springRestClient;

}

public boolean verify(String recaptchaResponse) {

URI verifyUri = URI

.create(String.format(RECAPTCHA_URL + "?secret=%s&response=%s", this.secretKey, recaptchaResponse));

JSONObject jsonResponse = null;

try {

jsonResponse = this.restClient.get(verifyUri);

} catch (JSONException e) {

logger.error("Error in Recaptcha Verification: " + e.getMessage());

return false;

}

boolean isVerified = false;

try {

isVerified = jsonResponse.getBoolean("success");

} catch (JSONException e) {

logger.error("Error in JSON processing: " + e.getMessage());

return false;

}

return isVerified;

}

}

Spring / Java App - 驗證服務器端代碼中的Recaptcha響應

以下代碼可用於驗證請求消息中到達的Recaptcha響應。

@PostMapping(value ="/signup")

public UserDTO signup(@RequestBody UserDTO userDTO, @RequestParam(name="g-recaptcha-response") String recaptchaResponse){

LOGGER.info("Initiating the user signup processing");

boolean verified = recaptchaVerifier.verify(recaptchaResponse);

if(!verified) {

userDTO.setErrorcode("RECAPTCHA_VERIFICATION_ERROR");

userDTO.setErrormsg("Recaptcha verification error. Please try again!");

return userDTO;

}

}

概要

在這篇文章中,您瞭解瞭如何在Angular和Spring / Java應用程序中實現Google Recaptcha。

你覺得這篇文章有用嗎?你對這篇文章有任何疑問或建議嗎?留下評論並提出問題,我將盡我所能解決您的疑問。


分享到:


相關文章: