This is a grails sample application to use captcha with spring security (s2) login function
$ grails create-app grails-captcha-sample
$ cd grails-captcha-sample
$ vi grails-app/conf/BuildConfig.groovy
plugins {
...
compile ":spring-security-core:1.2.7.1"
compile ":recaptcha:0.5.2"
}
$ grails compile
According to S2 Core Tutorials, you need to execute 's2-quickstart' command to setup User and Role domain objects etc.
$ grails s2-quickstart com.testapp User Role
$ vi grails-app/conf/BootStrap.groovy
import com.testapp.Role
import com.testapp.User
import com.testapp.UserRole
class BootStrap {
def init = { servletContext ->
def adminRole = new Role(authority: 'ROLE_ADMIN').save(flush: true)
def userRole = new Role(authority: 'ROLE_USER').save(flush: true)
def testUser = new User(username: 'me', enabled: true, password: 'password')
testUser.save(flush: true)
UserRole.create testUser, adminRole, true
assert User.count() == 1
assert Role.count() == 2
assert UserRole.count() == 1
}
def destroy = {
}
}
$ grails create-controller com.testapp.Secure
$ vi grails-app/controllers/com/testapp/SecureController.groovy
package com.testapp
import grails.plugins.springsecurity.Secured
class SecureController {
@Secured(['ROLE_ADMIN'])
def index() {
render 'Secure access only'
}
}
According to ReCaptcha Plugin Page, you need to create an account for Google ReCaptcha and get ReCaptcha API keys from there.
After getting keys, you can put them into RecaptchaConfig.groovy.
$ vi grails-app/conf/RecaptchaConfig.groovy
recaptcha {
// These keys are generated by the ReCaptcha service
publicKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
privateKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
...
}
This time, you'll add a captcha function on login page (auth.gsp) in addition to password authentication. For that end, you need to create a custom UserDetailsService according to Custom UserDetailsService.
$ grails create-service com.testapp.CaptchaUserDetails
$ vi grails-app/services/com/testapp/CaptchaUserDetailsService.groovy
(see the source file for actual contents)
Last pieces are DI definition for 'recaptchaService' in UserDetailsService and a customized GSP page with captcha (auth.gsp)
$ vi grails-app/conf/spring/resources.groovy
// Place your Spring DSL code here
beans = {
userDetailsService(com.testapp.CaptchaUserDetailsService) {
recaptchaService = ref('recaptchaService')
}
}
$ vi grails-app/views/login/auth.gsp
...
<p>
<recaptcha:ifEnabled>
<recaptcha:recaptcha />
<recaptcha:ifFailed>CAPTCHA Failed: ${session["recaptcha_error"]}</recaptcha:ifFailed>
</recaptcha:ifEnabled>
</p>
...
Now, you should have access control on /secure.
$ grails run-app
Try http://localhost:8080/grails-captcha-sample/secure with captcha as well as user/password ('me'/'password').