15.9. CAPTCHA
Though not strictly part of the security API, Seam provides a built-in CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) algorithm to prevent automated processes from interacting with your application.
15.9.1. Configuring the CAPTCHA Servlet
To use CAPTCHA, you need to configure the Seam Resource Servlet, which provides your pages with CAPTCHA challenge images. Add the following to
web.xml:
<servlet> <servlet-name>Seam Resource Servlet</servlet-name> <servlet-class>org.jboss.seam.servlet.SeamResourceServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Seam Resource Servlet</servlet-name> <url-pattern>/seam/resource/*</url-pattern> </servlet-mapping>
15.9.2. Adding a CAPTCHA to a form
It is easy to add a CAPTCHA challenge to a form:
<h:graphicImage value="/seam/resource/captcha"/> <h:inputText id="verifyCaptcha" value="#{captcha.response}" required="true"> <s:validate /> </h:inputText> <h:message for="verifyCaptcha"/>
That is all you need to do. The
graphicImage control displays the CAPTCHA challenge, and the inputText receives the user's response. The response is automatically validated against the CAPTCHA when the form is submitted.
15.9.3. Customizing the CAPTCHA algorithm
You can customize the CAPTCHA algorithm by overriding the built-in component:
@Name("org.jboss.seam.captcha.captcha") @Scope(SESSION) public class HitchhikersCaptcha extends Captcha { @Override @Create public void init() { setChallenge("What is the answer to life, the universe and everything?"); setCorrectResponse("42"); } @Override public BufferedImage renderChallenge() { BufferedImage img = super.renderChallenge(); img.getGraphics().drawOval(5, 3, 60, 14); //add an obscuring decoration return img; } }