当前位置:   article > 正文

recaptcha_与reCAPTCHA的Spring集成

recaptcha 集成

recaptcha

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

翻译自: https://www.javacodegeeks.com/2012/05/spring-integration-with-recaptcha.html

recaptcha

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/819727
推荐阅读
相关标签
  

闽ICP备14008679号