带有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。

你觉得这篇文章有用吗?你对这篇文章有任何疑问或建议吗?留下评论并提出问题,我将尽我所能解决您的疑问。


分享到:


相關文章: