OS...Windows 10 IDE...Eclipse 2020-3 Java...Open JDK 14 Servlet container ... Apache Tomcat 9.0.33
First, access the reCAPTCHA site. reCAPTCHA
Create with the + button.
Enter the information of your site.
Enter a descriptive name for the label.
For the reCAPTCHA type, I want to do "I'm not a robot", so I chose reCAPTCHA v2. Then, the "I am not a robot" checkbox will appear, so make sure it is selected.
For the domain, enter the domain for which "I am not a robot" is set. If you register the top domain, you can use it in subdomains. If you want to use it in the development environment, also register "localhost".
The owner ... well, you can do whatever you want.
Finally, accept the reCAPTCHA Terms of Service, choose to send the alert to the owner and click Send
The next screen will display two strings, so make a note of both.
This time, set it to "RecaptchaTest". (If you have already made it, use it.)
Let's create a new HTML file in the WebContent of the project created in Eclipse.
Or you can create it with an external editor and paste it into your project.
I don't usually write this kind of fucking code, but this time it's a sample. .. ..
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>reCAPTCHA sample</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="login" method="post">
ID:<input type="text" name="id"><br>
password:<input type="password" name="current-password">
<div class="g-recaptcha" data-sitekey="[Enter the string in the box above, out of the two strings displayed earlier.]"></div>
<input type="submit" value="Login">
</form>
</body>
</html>
The important thing is to read the script of the head and in the form
<div class="g-recaptcha" data-sitekey="[The one that was written in the box above that was displayed earlier]">
To put.
The "I'm not a robot" guy will be displayed where you put this div.
So, after completing the above HTML, let's try running it on the server. If it looks like the image below, it's okay! !!
Let's create a class (model) that queries Google's reCAPTCHA for results.
The mechanism is simple, put the specified parameters on the determined URL, POST, and JSON will be returned in the response.
Let's change the SECRET_KEY in the code below to the character string we got ~~~
package com.sakurai_shinya.recaptcha;
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;
public class RecaptchaAuthenticator {
private static final String URL = "https://www.google.com/recaptcha/api/siteverify";
private static final String SECRET_KEY = "[The string that was in the box below]";
public static boolean checkRecaptcha(String userToken) throws IOException {
String recaptchaResponse = post(new URL(URL), "secret=" + SECRET_KEY + "&response=" + userToken);
return recaptchaResponse.contains("\"success\": true,");
}
private static String post(URL url, String parameters) throws IOException {
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setDoOutput(true);
try (DataOutputStream dos = new DataOutputStream(con.getOutputStream())) {
dos.writeBytes(parameters);
dos.flush();
}
if (con.getResponseCode() != 200) {
throw new IOException("An error occurred while communicating with the server.");
}
StringBuilder sb = new StringBuilder();
try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
String tempStr;
while ((tempStr = in.readLine()) != null) {
sb.append(tempStr);
}
}
return sb.toString();
}
}
Since it is troublesome, I made the response as contains, OK if "" success ": true," was included, and NG if it was not included. If you want to do it properly, you should make an object properly and parse it.
I'll put all the Servlet code on it, but only at POST. Or rather, just look at POST
package com.sakurai_shinya.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sakurai_shinya.recaptcha.RecaptchaAuthenticator;
@WebServlet("/login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
super.service(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.sendRedirect("login.html");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
boolean recaptchaResult = false;
try {
recaptchaResult = RecaptchaAuthenticator.checkRecaptcha(request.getParameter("g-recaptcha-response"));
} catch (IOException e) {
response.getWriter().append("An error occurred while communicating with the reCAPTCHA authentication server." + e.toString());
}
if (recaptchaResult) {//reCAPTCHA success
//The process of matching the ID and password here.
String inputId = request.getParameter("id");
String inputPass = request.getParameter("current-password");
response.getWriter().append("Successful reCAPTCHA certification.<br>ID:" + inputId + "<br>password:" + inputPass);
} else {//reCAPTCHA failure
response.getWriter().append("ReCAPTCHA authentication failed.");
}
}
}
RecaptchaAuthenticator.checkRecaptcha(request.getParameter("g-recaptcha-response"));
If you call checkRecaptcha of the class you created earlier, the result will be true or false, or an exception will be returned. If true, reCAPTCHA will succeed, if false, reCAPTCHA will fail, and the exception will be an error.
By the way, if you paste the g-recaptcha guy on the form, the g-recaptcha-response parameters will be POSTed together with a mysterious force. You send this to Google's server to identify the user ~~~
Let's try it out!
Test with and without this check!
If you add data-theme = dark to the guy who has g-recaptcha, it will turn black. Now you can place it coolly even on a black site! !!
<div class="g-recaptcha" data-sitekey="6Lfx-eMUAAAAALrP774ZrvQa_AtguQhusF0M2W6s" data-theme="dark"></div>
Like this ↓
If you add hl = en to the GET parameter of api.js, it will be in English.
<script src="https://www.google.com/recaptcha/api.js?hl=en" async defer></script>
It gives a stylish impression, unlike Japanese, which breaks lines at strange positions.
By the way, other languages are on the reCAPTCHA guide. Language Codes | reCAPTCHA | Google Developers
Recommended Posts