Posts filed under 'JCaptcha'

How to configure JCaptcha with your Spring App

This is how I setup JCaptcha in my application. Following code snippet is for the test page I have created to test the JCaptcha and Spring integration

captchademoscreen

1) First create a controller which will generate a new Captcha for each session based on session id

package com.example.web.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.example.domain.LoginCommand;
import com.example.logger.LoginLogger;

public class CaptchaController extends LoginBaseController {

    public CaptchaController(){
        setCommandClass(LoginCommand.class);
    }

    @Override
    protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors,
            Map controlModel) throws Exception {

         byte[] captchaChallengeAsJpeg = null;
           // the output stream to render the captcha image as jpeg into
            ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
            try {
            // get the session id that will identify the generated captcha.
            //the same id must be used to validate the response, the session id is a good candidate!

            String captchaId = request.getSession().getId();
            LoginLogger.debug(this, "Captcha ID which gave the image::" + captchaId);
            // call the ImageCaptchaService getChallenge method
                BufferedImage challenge = ((ImageCaptchaService)getCaptchaService()).getImageChallengeForID(captchaId, request.getLocale());

                // a jpeg encoder
                JPEGImageEncoder jpegEncoder =
                        JPEGCodec.createJPEGEncoder(jpegOutputStream);
                jpegEncoder.encode(challenge);
            } catch (IllegalArgumentException e) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return null;
            } catch (CaptchaServiceException e) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return null;
            }

            captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

            // flush it in the response
            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            //response.setContentType("image/jpeg");
//            response.getOutputStream().write(jpegOutputStream);
            ServletOutputStream responseOutputStream =
                response.getOutputStream();
            responseOutputStream.write(captchaChallengeAsJpeg);
            responseOutputStream.flush();
            responseOutputStream.close();

        return null;
    }

}

Please note that your implementation can vary. The only thing you want is a simple Servlet which will execute the code in showForm method above. In my case I am relying on Spring framework to execute this code because in the JSP where you show Captcha image I have written something like this
<img id=”captchaImage” src=”http://localhost:8080/LoginApplication/captcha.htm”>. In my application the URL captcha.htm is wired to this controller. But you can choose to have a simple servlet mapped instead of a Spring Controller.

2) Make the following entries in your Spring config files to configure JCaptcha

    
    

        

    
        

                
            
        
    

    
        
        
    

    
        
    

    
        toddlist
    

    
        
        
        
    

    
        40
        50
        

                
            
        
    

    
        Arial
        0
        10
    

    
        300
        100
    

    
        
            3
        
        
            5
        
        
            
        
    

    
        0
        255
        0
    

    
        0
        0
        0
    

    
        
        180
        180000
    
    

For test purpose I have used a Simple Text Captcha.

3) To test create a command,controller and JSP like this

public class LoginCommand implements Serializable {
    private String verificationTextForForgotPass;
    //getter and setter methods
}
package com.example.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.octo.captcha.service.CaptchaServiceException;
import com.example.domain.LoginCommand;

public class CaptchaDemoController extends LoginBaseController {
	private CaptchaService captchaService;
	//Getter and setter for captchaService

    public CaptchaDemoController() {
        setCommandClass(LoginCommand.class);
    }

    @Override
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        LoginCommand command = new LoginCommand();

        return command;
    }

    @Override
    protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,
            Object command, BindException errors) throws Exception {
        boolean isResponseCorrect = false;
        String sessionId = request.getSession().getId();
        //retrieve the response
        String verificationText = ((LoginCommand) command).getVerificationTextForForgotPass();

        // Call the Service method
        try {
            isResponseCorrect = getCaptchaService().validateResponseForID(sessionId, verificationText);
        }
        catch (CaptchaServiceException e) {
            //should not happen, may be thrown if the id is not valid
        }

		//You can do whatever you want to based on the response
        response.getWriter().write(String.valueOf(isResponseCorrect));

        return null;
    }
}

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>





	

	Enter the text here



As you can see the JSP will just show one Captcha Image and a text box where you can enter the Image text. The controller will verify the entered text and display true or false based on the result. You can implement your logic here for the Captcha verification result.

4) Finally make the following entries in your corresponding spring config file


    


captchaDemoController
captchaController
            
        
    


   

   
    



    

Oops I forgot to mention, you should have JCaptcha jars in your classpath for this example to work ;)
I have written this post using the working code I have. I might have missed some configuration in this post. Let me know if you get any error. I will update the post.

1 comment November 11th, 2008


Add to Technorati Favorites

Blogroll

Categories

Archives

 

March 2010
M T W T F S S
« Dec    
1234567
891011121314
15161718192021
22232425262728
293031