酷播亮新聞
最棒的知識補給站

帶有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的登錄檔單看起來如下。該工作示例可以在此註冊頁面上找到。

在登入/註冊元件中處理程式碼,以便除非使用者點選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

//

}

}

建立一個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

@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;

}

}

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;

}

}

以下程式碼可用於驗證請求訊息中到達的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。

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

如有侵權請來信告知:酷播亮新聞 » 帶有Angular和Spring App的Google Recaptcha示例