因Google reCaptcha v1停用,如何在Spring框架中实现reCaptcha v2?
Hey there! Sorry to hear your reCaptcha v1 stopped working after Google discontinued it—let's walk through getting reCaptcha v2 up and running in your Spring app, step by step.
1. Get Your reCaptcha v2 Credentials
First, head over to the Google reCaptcha admin console to register your application. You'll get two critical keys:
- Site Key: Used in your frontend to render the reCaptcha widget
- Secret Key: Kept secure in your backend for verifying user responses
Store these in your Spring app's configuration (e.g., application.properties):
recaptcha.site-key=your-site-key-here recaptcha.secret-key=your-secret-key-here
2. Integrate the Frontend Widget
Add the reCaptcha script to your registration page's <head> section:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
Then, place the widget inside your registration form where you want it to appear:
<div class="g-recaptcha" data-sitekey="${recaptcha.site-key}"></div>
When the user submits the form, the widget will automatically include a g-recaptcha-response parameter in the form data—this is the value you'll validate on the backend.
3. Backend Validation in Spring
Create a service class to handle reCaptcha verification. This class will send a request to Google's verification endpoint and parse the response.
Example Service Class
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import java.util.Map; @Service public class RecaptchaService { @Value("${recaptcha.secret-key}") private String secretKey; private static final String VERIFICATION_URL = "https://www.google.com/recaptcha/api/siteverify"; public boolean verifyRecaptcha(String response, String remoteIp) { RestTemplate restTemplate = new RestTemplate(); Map<String, String> params = new HashMap<>(); params.put("secret", secretKey); params.put("response", response); params.put("remoteip", remoteIp); RecaptchaResponse recaptchaResponse = restTemplate.postForObject(VERIFICATION_URL, params, RecaptchaResponse.class); return recaptchaResponse != null && recaptchaResponse.isSuccess(); } // Helper class to map the JSON response from Google private static class RecaptchaResponse { private boolean success; // You can add other fields like error-codes if needed for debugging public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } } }
Use the Service in Your Controller
In your registration controller, retrieve the g-recaptcha-response parameter from the request, along with the user's IP, then call the verification service before processing the registration:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; @RestController public class RegistrationController { @Autowired private RecaptchaService recaptchaService; @PostMapping("/register") public String registerUser(@RequestParam("g-recaptcha-response") String recaptchaResponse, HttpServletRequest request) { String userIp = request.getRemoteAddr(); boolean isRecaptchaValid = recaptchaService.verifyRecaptcha(recaptchaResponse, userIp); if (!isRecaptchaValid) { return "reCaptcha verification failed. Please try again."; } // Proceed with your user registration logic here return "Registration successful!"; } }
Documentation Notes
Google's official reCaptcha v2 documentation covers all the details, including different widget rendering options (like invisible reCaptcha), error handling, and security best practices. For Spring-specific integration, you can also explore community-maintained starters that wrap this logic into auto-configured beans, but the core verification flow we outlined above aligns with the official specs.
内容的提问来源于stack exchange,提问作者Abhilash Shajan




