博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
百家与g对比oogle_如何在Java Web应用程序中集成Google reCAPTCHA
阅读量:2532 次
发布时间:2019-05-11

本文共 9353 字,大约阅读时间需要 31 分钟。

百家与g对比oogle

I never liked Captchas because the burden was always on end user to understand the letters and prove that he is a human and not a software bot. But when I recently saw new Google reCAPTCHA on a website, I instantly liked it.

我从来不喜欢Captchas,因为最终用户总是要负担理解字母并证明他是人而不是软件机器人的重担。 但是,当我最近在网站上看到新的Google reCAPTCHA时,我立即喜欢上它。

Because all we need is to check a box and it will figure out if you are a human or robot. Google is calling it No CAPTCHA reCAPTCHA experience and it uses an advanced risk analysis engine and adaptive CAPTCHAs to keep automated software from engaging in abusive activities on your site.

因为我们只需要选中一个框,它就会确定您是人类还是机器人。 Google称其没有CAPTCHA reCAPTCHA经验 ,它使用高级风险分析引擎和自适应CAPTCHA来防止自动化软件参与您网站上的滥用行为。

So that formed the basis of this post where I will show you how to utilize Google reCAPTCHA in your java based web application.

这样就构成了本文的基础,在这里我将向您展示如何在基于Java的Web应用程序中使用Google reCAPTCHA。

Before we move on with our project, first thing you need to do is go to and sign up. After that you will get a Site key that is used to display the reCaptcha widget on your web pages. You will also get a Secret key that should be kept secret and used in communicating with Google server to verify the captcha response.

在继续进行项目之前,您需要做的第一件事就是转到并注册。 之后,您将获得一个Site键 ,用于在网页上显示reCaptcha小部件。 您还将获得一个秘密密钥 ,该密钥应保密,并用于与Google服务器通信以验证验证码响应。

After I registered a test site, I got below keys and I will utilize them in my project. Note that while signup you also need to provide domain name and the keys will work only on that domain name. Also keys will always work on localhost, so I can easily test it on my local server.

注册测试站点后,我得到了下面的按键,并将在我的项目中使用它们。 请注意,在注册时,您还需要提供域名,并且密钥仅适用于该域名。 而且,密钥将始终在localhost上运行,因此我可以在本地服务器上轻松对其进行测试。

Now we can head over to our example project. We will have a login page where user will enter username and password, apart from that he will also have to solve reCaptcha and submit the form.

现在我们可以转到示例项目。 我们将有一个登录页面,用户将在其中输入用户名和密码,除此之外,他还必须解决reCaptcha并提交表格。

Once the form is submitted, username and password will be validated in our application, whereas we will send the captcha response with secret key to Google reCaptcha server and get the response.

提交表单后,用户名和密码将在我们的应用程序中得到验证,而我们会将带有密码的验证码响应发送到Google reCaptcha服务器并获得响应。

The response from Google reCaptcha is a JSON with a success boolean field, if validated success value will be true otherwise it will be false. I will use to parse the response JSON.

Google reCaptcha的响应是带有成功布尔值字段的JSON,如果已验证的成功值将为true,否则为false。 我将使用来解析响应JSON。

Below image shows our final project in Eclipse.

下图显示了我们在Eclipse中的最终项目。

To get the project skeleton, just create a “Dynamic Web Project” in Eclipse and then convert it to Maven project. Just add below dependency in pom.xml file for JSON API.

要获得项目框架,只需在Eclipse中创建一个“动态Web项目”,然后将其转换为Maven项目。 只需在pom.xml文件的JSON API中添加以下依赖项即可。

org.glassfish
javax.json
1.0.2

Let’s look into each of the components one by one.

让我们逐一研究每个组件。

使用Google reCAPTCHA查看页面 (View Page with Google reCAPTCHA)

Below is our login html page code.

以下是我们的登录html页面代码。

login.html

login.html

Login Page
Username:
Password:

We need to add Google reCaptcha JS file in the HTML head section and then add <div class="g-recaptcha" data-sitekey="Site-key"></div> in our form to get the reCaptcha widget. That’s all at the client side, it’s really this simple!

我们需要在HTML头部添加Google reCaptcha JS文件,然后在表单中添加<div class="g-recaptcha" data-sitekey="Site-key"></div>以获得reCaptcha小部件。 就在客户端,这就是这么简单!

Once user is validated he will be sent to below success page.

用户通过验证后,将被发送到成功页面下方。

LoginSuccess.jsp

LoginSuccess.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"    pageEncoding="US-ASCII"%>
Login Success Page

Hi Pankaj, Login successful.

Login Page

登录Servlet (Login Servlet)

Below is our simple LoginServlet.java servlet code where we are validating username and password fields. For simplicity, they are embedded as WebInitParam in the servlet code itself. Note that you need to use Servlet 3 to use these annotations, so you need to use Tomcat-7 or later versions that support servlet spec 3.

以下是我们简单的LoginServlet.java Servlet代码,用于验证用户名和密码字段。 为简单起见,它们作为WebInitParam嵌入在Servlet代码本身中。 请注意,您需要使用Servlet 3来使用这些注释,因此您需要使用支持Servlet规范3的Tomcat-7或更高版本。

package com.journaldev.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.annotation.WebInitParam;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.journaldev.utils.VerifyRecaptcha;/** * Servlet implementation class LoginServlet */@WebServlet(description = "Login Servlet", urlPatterns = { "/LoginServlet" }, initParams = {		@WebInitParam(name = "user", value = "Pankaj"),		@WebInitParam(name = "password", value = "journaldev") })public class LoginServlet extends HttpServlet {	private static final long serialVersionUID = -6506682026701304964L;	protected void doPost(HttpServletRequest request,			HttpServletResponse response) throws ServletException, IOException {		// get request parameters for userID and password		String user = request.getParameter("user");		String pwd = request.getParameter("pwd");		// get reCAPTCHA request param		String gRecaptchaResponse = request				.getParameter("g-recaptcha-response");		System.out.println(gRecaptchaResponse);		boolean verify = VerifyRecaptcha.verify(gRecaptchaResponse);		// get servlet config init params		String userID = getServletConfig().getInitParameter("user");		String password = getServletConfig().getInitParameter("password");		// logging example		System.out.println("User=" + user + "::password=" + pwd + "::Captcha Verify"+verify);		if (userID.equals(user) && password.equals(pwd) && verify) {			response.sendRedirect("LoginSuccess.jsp");		} else {			RequestDispatcher rd = getServletContext().getRequestDispatcher(					"/login.html");			PrintWriter out = response.getWriter();			if (verify) {				out.println("Either user name or password is wrong.");			} else {				out.println("You missed the Captcha.");			}			rd.include(request, response);		}	}}

Once form with captcha is submitted, we get “g-recaptcha-response” request parameter that is required to send for verification. The last part is the utility class to send POST request for verification and parse the JSON response and return accordingly.

提交带有验证码的表单后,我们将获得“ g-recaptcha-response”请求参数,该参数需要发送以进行验证。 最后一部分是实用程序类,用于发送POST请求进行验证,解析JSON响应并相应地返回。

package com.journaldev.utils;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.StringReader;import java.net.URL;import javax.json.Json;import javax.json.JsonObject;import javax.json.JsonReader;import javax.net.ssl.HttpsURLConnection;public class VerifyRecaptcha {	public static final String url = "https://www.google.com/recaptcha/api/siteverify";	public static final String secret = "6LdMAgMTAAAAAJOAqKgjWe9DUujd2iyTmzjXilM7";	private final static String USER_AGENT = "Mozilla/5.0";	public static boolean verify(String gRecaptchaResponse) throws IOException {		if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {			return false;		}				try{		URL obj = new URL(url);		HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();		// add reuqest header		con.setRequestMethod("POST");		con.setRequestProperty("User-Agent", USER_AGENT);		con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");		String postParams = "secret=" + secret + "&response="				+ gRecaptchaResponse;		// Send post request		con.setDoOutput(true);		DataOutputStream wr = new DataOutputStream(con.getOutputStream());		wr.writeBytes(postParams);		wr.flush();		wr.close();		int responseCode = con.getResponseCode();		System.out.println("\nSending 'POST' request to URL : " + url);		System.out.println("Post parameters : " + postParams);		System.out.println("Response Code : " + responseCode);		BufferedReader in = new BufferedReader(new InputStreamReader(				con.getInputStream()));		String inputLine;		StringBuffer response = new StringBuffer();		while ((inputLine = in.readLine()) != null) {			response.append(inputLine);		}		in.close();		// print result		System.out.println(response.toString());				//parse JSON response and return 'success' value		JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));		JsonObject jsonObject = jsonReader.readObject();		jsonReader.close();				return jsonObject.getBoolean("success");		}catch(Exception e){			e.printStackTrace();			return false;		}	}}

That’s all. Our application is ready, below are the response pages we get based on user inputs.

就这样。 我们的应用程序已准备就绪,下面是根据用户输入获得的响应页面。

Login Page with Google Recaptcha Widget

带有Google Recaptcha小部件的登录页面

Google Recaptcha Validated at client side

Google Recaptcha已在客户端验证

Response page after server side Google Recaptcha Validation

服务器端Google Recaptcha验证后的响应页面

Response where Recaptcha was not solved

未解决Recaptcha的响应

Recaptcha Solved but user/password didn’t match

重新解决,但用户/密码不匹配

You can download the project from below link and play around with it to learn more.

您可以从下面的链接下载该项目并进行试用以了解更多信息。

翻译自:

百家与g对比oogle

转载地址:http://rllzd.baihongyu.com/

你可能感兴趣的文章
jQueru中数据交换格式XML和JSON对比
查看>>
form表单序列化后的数据转json对象
查看>>
[PYTHON]一个简单的单元測试框架
查看>>
iOS开发网络篇—XML数据的解析
查看>>
[BZOJ4303]数列
查看>>
一般处理程序在VS2012中打开问题
查看>>
C语言中的++和--
查看>>
thinkphp3.2.3入口文件详解
查看>>
POJ 1141 Brackets Sequence
查看>>
Ubuntu 18.04 root 使用ssh密钥远程登陆
查看>>
Servlet和JSP的异同。
查看>>
虚拟机centOs Linux与Windows之间的文件传输
查看>>
ethereum(以太坊)(二)--合约中属性和行为的访问权限
查看>>
IOS内存管理
查看>>
middle
查看>>
[Bzoj1009][HNOI2008]GT考试(动态规划)
查看>>
Blob(二进制)、byte[]、long、date之间的类型转换
查看>>
OO第一次总结博客
查看>>
day7
查看>>
iphone移动端踩坑
查看>>