日期:2014-05-20  浏览次数:20832 次

在Play framework2.0.4 添加google ReCaptcah验证码校验

原文链接:http://techminded.net/blog/adding-captcha-in-playframework2.html

之前我们讨论了在PlayFramework2里面使用验证码。但是马上你就会发现用reCaptcha插件来完成这项任务会更轻松。为了方便你的理解,我的例子会很简陋,你可以在深入理解之后好好修饰一下它。

首先去这个网址获得公钥和私钥http://recaptcha.net/,注意一定要选择生成全局Key(global key),要不然你就没有办法在localhost本机环境里测试。

然后别忘了在你的/conf/application.conf里面增加配置属性:

recaptcha.publickey=6Lcpy9YSAAAAAKPK5T8tdO5WbiRPkKENziunk0c2
# recaptcha global public key
recaptcha.privatekey=6Lcpy9YSAAAAANlSJ-iw9GDSKFYX5HktGbs-oG7D
# recaptcha global private key

接着把recaptcha4j类库添加到你的依赖里,具体在你的/project/Build.scala里把下面的代码放到你的依赖语句块里。


val appDependencies = Seq(
  "net.tanesha.recaptcha4j"%"recaptcha4j"%"0.0.7"
)

然后在Play 控制台里运行‘reload’命令重新加载你的配置,运行‘dependencies’命令来检查recaptcha 是否安装成功。

现在我们需要新建一个view单例以备我们在显示验证码时候调用。在/app/views里创建ReCaptcha.scala

package views
 
 
importjava.util.Properties
importnet.tanesha.recaptcha.ReCaptchaFactory
importnet.tanesha.recaptcha.ReCaptchaImpl
importnet.tanesha.recaptcha.ReCaptchaResponse
importplay.api.Play.current
importplay.api.Logger
 
 
object ReCaptcha {
 
  def publicKey(): String = {
    current.configuration.getString("recaptcha.publickey").get
  }
  def privateKey(): String = {
    current.configuration.getString("recaptcha.privatekey").get
  }
  def render(): String = {
    ReCaptchaFactory.newReCaptcha(publicKey(),
                    privateKey(), false).createRecaptchaHtml(null,newProperties)
  }
}

这个类一共包括3个方法:publicKey()、privateKey()用来从配置文件里获取key,render()用来在页面里生成验证码。

现在你可以在你的表单里添加如下代码来看一看他听不听话: 

@Html(views.ReCaptcha.render())

运气好的话你应该能看到google的验证码模块的尊荣了。现在我们来对输入合法性进行校验,在ReCapcha类里面添加如下的方法:

?
def check(addr: String, challenge: String, response: String): Boolean = {
  val reCaptcha = newReCaptchaImpl()
  reCaptcha.setPrivateKey(privateKey())
  val reCaptchaResponse = reCaptcha.checkAnswer(addr, challenge, response)
  reCaptchaResponse.isValid()
}

好吧,在views标签里添加校验是个弱智做法,不过我保证过这个例子是简单易懂的哦偷笑,我现在用的play-recaptcha 3rd-party module 模块设计的比较精良,你可以去参考一下。

https://github.com/orefalo/play-recaptcha/

为了真正的校验一把,你的表单里应但有下面这些代码:

val captchaForm = Form[(String, String)](
 tuple(
    "recaptcha_challenge_field"-> nonEmptyText,
    "recaptcha_response_field"-> nonEmptyText
  )
 )
captchaForm.bindFromRequest.fold(
  failure => ( BadRequest("Captcha Param Error")),
  {case(q, a) => {
      if(ReCaptcha.check(addr, q, a)) {
        // code in case captcha is valid goes here
      }else{
        BadRequest("Captcha Validation Error")
      }
    }
  }
)

你还可以在你的应用表单里定义(apply/unapply)来取消校验。

译注:完

原文链接:http://techminded.net/blog/adding-captcha-in-playframework2.html