recaptcha
有时我们只需要CAPTCHA ,这是一个可悲的事实。
今天,我们将学习如何与reCAPTCHA集成。
因为主题本身并不是特别有趣和高级,所以我们将通过使用Spring Integration处理低级细节来过度设计(?)。
Google决定使用reCAPTCHA的决定取决于两个因素:(1)这是一种适度良好的CAPTCHA实施,内置了对视力障碍者的内置支持的体面图像;(2)将CAPTCHA外包可使我们在服务器端保持无状态。
更不用说我们在图书数字化方面有所帮助。
第二个原因实际上很重要。
通常,您必须在服务器端生成CAPTCHA,并将预期结果存储在例如用户会话中。
当响应返回时,您比较预期的并输入了CAPTCHA解决方案。
有时我们不想在服务器端存储任何状态,更不用说实现验证码并不是特别有意义的任务。
因此,拥有现成的,可以接受的东西真是太好了。
完整的源代码一如既往地可用,我们从一个没有任何验证码的简单Spring MVC Web应用程序开始。
reCAPTCHA是免费的,但需要注册,因此第一步是在我们的示例项目中使用并生成您的公钥/私钥和填写的
app.properties
配置文件。
要在表单上显示reCAPTCHA并将其包括在表单中,只需添加JavaScript库:
- <div id="recaptcha"> </div>
- ...
- <script src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
并将reCAPTCHA小部件放置在您喜欢的任何位置:
- Recaptcha.create("${recaptcha_public_key}",
- "recaptcha",
- {
- theme: "white",
- lang : 'en'
- }
- );
官方文档非常简洁和描述性强,因此我不会深入探讨这一细节。
当您在
<form/>
包含此小部件时,当用户提交时,您将收到两个额外的字段: recaptcha_response_field
和recaptcha_challenge_field
。
第一个是用户键入的实际文本,第二个是每个请求生成的隐藏令牌。
reCAPTCHA服务器可能会将它用作会话密钥,但是我们不在乎,我们要做的就是将此字段进一步传递给reCAPTCHA服务器 。
我将使用HttpClient 4对外部服务器执行HTTP请求,并在Scala中执行一些巧妙的模式匹配来解析响应:
- trait ReCaptchaVerifier {
- def validate(reCaptchaRequest: ReCaptchaSecured): Boolean
-
- }
-
- @Service
- class HttpClientReCaptchaVerifier @Autowired()(
- httpClient: HttpClient,
- servletRequest: HttpServletRequest,
- @Value("${recaptcha_url}") recaptchaUrl: String,
- @Value("${recaptcha_private_key}") recaptchaPrivateKey: String
- ) extends ReCaptchaVerifier {
-
- def validate(reCaptchaRequest: ReCaptchaSecured): Boolean = {
- val post = new HttpPost(recaptchaUrl)
- post.setEntity(new UrlEncodedFormEntity(List(
- new BasicNameValuePair("privatekey", recaptchaPrivateKey),
- new BasicNameValuePair("remoteip", servletRequest.getRemoteAddr),
- new BasicNameValuePair("challenge", reCaptchaRequest.recaptchaChallenge),
- new BasicNameValuePair("response", reCaptchaRequest.recaptchaResponse)))
- )
- val response = httpClient.execute(post)
- isReCaptchaSuccess(response.getEntity.getContent)
- }
-
- private def isReCaptchaSuccess(response: InputStream) = {
- val responseLines = Option(response) map {
- Source.fromInputStream(_).getLines().toList
- } getOrElse Nil
- responseLines match {
- case "true" :: _ => true
- case "false" :: "incorrect-captcha-sol" :: _=> false
- case "false" :: msg :: _ => throw new ReCaptchaException(msg)
- case resp => throw new ReCaptchaException("Unrecognized response: " + resp.toList)
- }
- }
-
- }
-
- class ReCaptchaException(msg: String) extends RuntimeException(msg)
唯一缺少的部分是
ReCaptchaSecured
特性,它封装了前面提到的两个reCAPTCHA字段。
为了使用reCAPTCHA保护任何Web表单,我只是在扩展此模型:
- trait ReCaptchaSecured {
- @BeanProperty var recaptchaChallenge = ""
- @BeanProperty var recaptchaResponse = ""
- }
-
- class NewComment extends ReCaptchaSecured {
- @BeanProperty var name = ""
- @BeanProperty var contents = ""
- }
整个
CommentsController.scala
并不相关。
但是结果是!
这样就可以了,但是显然并不是很壮观。
对于使用Spring Integration替换低级HttpClient调用,您说什么?
ReCaptchaVerifier
接口(特征)保持不变,因此不必更改客户端代码。
但是我们将HttpClientReCaptchaVerifier
重构为两个单独的,较小的,相对高级的抽象类:
- @Service
- class ReCaptchaFormToHttpRequest @Autowired() (servletRequest: HttpServletRequest, @Value("${recaptcha_private_key}") recaptchaPrivateKey: String) {
-
- def transform(form: ReCaptchaSecured) = Map(
- "privatekey" -> recaptchaPrivateKey,
- "remoteip" -> servletRequest.getRemoteAddr,
- "challenge" -> form.recaptchaChallenge,
- "response" -> form.recaptchaResponse).asJava
-
- }
-
- @Service
- class ReCaptchaServerResponseToResult {
-
- def transform(response: String) = {
- val responseLines = response.split('\n').toList
- responseLines match {
- case "true" :: _ => true
- case "false" :: "incorrect-captcha-sol" :: _=> false
- case "false" :: msg :: _ => throw new ReCaptchaException(msg)
- case resp => throw new ReCaptchaException("Unrecognized response: " + resp.toList)
- }
- }
-
- }
请注意,我们不再需要实现
ReCaptchaVerifier
,Spring Integration将为我们做到这一点。
我们只需要告诉我们框架应该如何使用上面提取的构建块。
我想我还没有描述Spring Integration是什么以及它是如何工作的。
简而言之,它是企业集成模式的非常纯净的实现(有些人可能将其称为ESB)。
消息流是使用XML描述的,可以嵌入到标准Spring XML配置中:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://www.springframework.org/schema/integration"
- xmlns:http="http://www.springframework.org/schema/integration/http"
- xsi:schemaLocation="
- http://www.springframework.org/schema/integration
- http://www.springframework.org/schema/integration/spring-integration.xsd
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/integration/http
- http://www.springframework.org/schema/integration/http/spring-integration-http.xsd
- ">
-
- <!-- configuration here -->
-
- </beans:beans>
在我们的案例中,我们将描述从
HttpClientReCaptchaVerifier
Java接口/ Scala特征到reCAPTCHA服务器再返回的消息流。
在必须将ReCaptchaSecured
对象转换为HTTP请求并将HTTP响应转换为有意义的结果的方式上,该方法从接口透明返回。
- <gateway id="ReCaptchaVerifier" service-interface="com.blogspot.nurkiewicz.recaptcha.ReCaptchaVerifier" default-request-channel="reCaptchaSecuredForm"/>
-
- <channel id="reCaptchaSecuredForm" datatype="com.blogspot.nurkiewicz.web.ReCaptchaSecured"/>
-
- <transformer input-channel="reCaptchaSecuredForm" output-channel="reCaptchaGoogleServerRequest" ref="reCaptchaFormToHttpRequest"/>
-
- <channel id="reCaptchaGoogleServerRequest" datatype="java.util.Map"/>
-
- <http:outbound-gateway
- request-channel="reCaptchaGoogleServerRequest"
- reply-channel="reCaptchaGoogleServerResponse"
- url="${recaptcha_url}"
- http-method="POST"
- extract-request-payload="true"
- expected-response-type="java.lang.String"/>
-
- <channel id="reCaptchaGoogleServerResponse" datatype="java.lang.String"/>
-
- <transformer input-channel="reCaptchaGoogleServerResponse" ref="reCaptchaServerResponseToResult"/>
尽管有大量的XML,但是整个消息流还是非常简单的。
首先我们定义网关 ,它是Java接口和Spring Integration消息流之间的桥梁。
ReCaptchaVerifier.validate()
的参数稍后变成一条消息 ,该消息发送到reCaptchaSecuredForm
channel 。
ReCaptchaSecured
对象从该通道传递到ReCaptchaFormToHttpRequest
转换器 。
转换器的目的是从ReCaptchaSecured
对象到Java映射进行两次转换,以表示一组键值对。
稍后,此映射(通过reCaptchaGoogleServerRequest
通道)传递到http:outbound-gateway
。
该组件的职责是将先前创建的地图转换为HTTP请求并将其发送到指定的地址。
当响应返回时,它被发送到
reCaptchaGoogleServerResponse
通道。
ReCaptchaServerResponseToResult
转换器将采取行动,将HTTP响应转换为业务结果(布尔值)。
最终,转换器结果被路由回网关。
默认情况下,所有操作都是同步发生的,因此我们仍然可以使用简单的Java接口进行reCAPTCHA验证。
信不信由你,这一切正常。
我们不再使用
HttpClient
(猜测一切都比HttpClient 4 API更好……),而不是一个“巨大”的类,我们有一组较小的,集中的,易于测试的类。
该框架处理接线和底层细节。
精彩?
让我通过引用以上介绍的结论来总结我们的工作:在架构收益与开发有效性之间取得平衡 。
Spring Integration能够从各种异构源(如JMS,关系数据库甚至FTP)接收数据,以多种方式聚合,拆分,解析和过滤消息,最后使用最奇特的协议将其进一步发送。
手工编写所有代码是一项非常繁琐且容易出错的任务。
另一方面,有时我们只是不需要所有的幻想,而弄脏我们的手(例如,通过执行手动HTTP请求并解析响应)则更加简单易懂。
在盲目地将整个体系结构基于非常高级的抽象或基于手工编码的低级过程之前,请考虑一下后果和平衡。
没有解决方案可以解决所有问题。
您发现哪个版本的reCAPTCHA集成更好?
翻译自: https://www.javacodegeeks.com/2012/05/spring-integration-with-recaptcha.html
recaptcha