`

【转】jcaptcha验证码

阅读更多

1、从jcaptcha官方网站下载jcaptcha的发行包,并将其发行包中的jar文件考贝到本地项目WEB-INF目录下的lib目录中。

官方网址http://jcaptcha.sourceforge.net/

2、在web.xml文件中配置

Java代码  收藏代码
  1. <servlet>  
  2.      <servlet-name>jcaptcha</servlet-name>  
  3.      <servlet-class>cn.hxex.order.core.jcaptcha.ImageCaptchaServlet</servlet-class>  
  4.      <load-on-startup>3</load-on-startup>  
  5.  </servlet>  
  6.   
  7.  <servlet-mapping>  
  8.      <servlet-name>jcaptcha</servlet-name>  
  9.      <url-pattern>/captcha.jpg</url-pattern>  
  10.  </servlet-mapping>  



3、jcaptcha在spring中的配置

Java代码  收藏代码
  1.     <bean id="channelProcessingFilter"  
  2.           class="org.acegisecurity.securechannel.ChannelProcessingFilter">  
  3.         <property name="channelDecisionManager">  
  4.             <ref local="channelDecisionManager"/>   
  5.         </property>  
  6.         <property name="filterInvocationDefinitionSource">  
  7.             <value>  
  8.                 CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON  
  9.                 PATTERN_TYPE_APACHE_ANT  
  10.                 /j_security_check=REQUIRES_CAPTCHA_ONCE_ABOVE_THRESOLD_REQUESTS  
  11.             </value>  
  12.         </property>  
  13.     </bean>  
  14.   
  15.     <bean id="channelDecisionManager"  
  16.           class="org.acegisecurity.securechannel.ChannelDecisionManagerImpl">  
  17.         <property name="channelProcessors">   
  18.             <list>  
  19.                 <ref local="testOnceAfterMaxRequestsCaptchaChannelProcessor"/>  
  20.                 <ref local="alwaysTestAfterTimeInMillisCaptchaChannelProcessor"/>  
  21.                 <ref local="alwaysTestAfterMaxRequestsCaptchaChannelProcessor"/>  
  22.                 <ref local="alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor"/>  
  23.             </list>  
  24.         </property>  
  25.     </bean>  
  26.   
  27.     <!-- REQUIRES_CAPTCHA_ONCE_ABOVE_THRESOLD_REQUESTS -->  
  28.     <bean id="testOnceAfterMaxRequestsCaptchaChannelProcessor"  
  29.           class="org.acegisecurity.captcha.TestOnceAfterMaxRequestsCaptchaChannelProcessor">  
  30.         <property name="thresold">  
  31.             <value>0</value>  
  32.         </property>  
  33.         <property name="entryPoint">  
  34.             <ref bean="captchaEntryPoint"/>  
  35.         </property>  
  36.     </bean>  
  37.   
  38.     <!-- REQUIRES_CAPTCHA_ABOVE_THRESOLD_REQUESTS -->  
  39.     <bean id="alwaysTestAfterMaxRequestsCaptchaChannelProcessor"  
  40.           class="org.acegisecurity.captcha.AlwaysTestAfterMaxRequestsCaptchaChannelProcessor">  
  41.         <property name="thresold">  
  42.             <value>5</value>  
  43.         </property>  
  44.         <property name="entryPoint">  
  45.             <ref bean="captchaEntryPoint"/>  
  46.         </property>  
  47.     </bean>  
  48.   
  49.     <!-- REQUIRES_CAPTCHA_AFTER_THRESOLD_IN_MILLIS -->  
  50.     <bean id="alwaysTestAfterTimeInMillisCaptchaChannelProcessor"  
  51.           class="org.acegisecurity.captcha.AlwaysTestAfterTimeInMillisCaptchaChannelProcessor">  
  52.         <property name="thresold">  
  53.             <value>5000</value>  
  54.         </property>  
  55.         <property name="entryPoint">  
  56.             <ref bean="captchaEntryPoint"/>  
  57.         </property>  
  58.     </bean>  
  59.   
  60.     <!-- REQUIRES_CAPTCHA_BELOW_AVERAGE_TIME_IN_MILLIS_REQUESTS -->  
  61.        
  62.     <bean  
  63.             id="alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor"  
  64.             class="org.acegisecurity.captcha.AlwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor">  
  65.         <property name="thresold">  
  66.             <value>20000</value>  
  67.         </property>  
  68.         <property name="entryPoint">  
  69.             <ref bean="captchaEntryPoint"/>  
  70.         </property>  
  71.     </bean>  
  72.   
  73.     <bean id="captchaEntryPoint"  
  74.           class="org.acegisecurity.captcha.CaptchaEntryPoint">  
  75.         <!--验证码验证失败后转向的页面!-->  
  76.         <property name="captchaFormUrl">  
  77.             <value>/admin/login.jsp?login_error=code_error</value>  
  78.         </property>  
  79.         <property name="includeOriginalRequest">  
  80.             <value>false</value>  
  81.         </property>  
  82.         <property name="includeOriginalParameters">  
  83.             <value>false</value>  
  84.         </property>  
  85.     </bean>  
  86.   
  87.     <bean id="captchaValidationProcessingFilter"  
  88.           class="org.acegisecurity.captcha.CaptchaValidationProcessingFilter">  
  89.         <property name="captchaService">  
  90.             <ref bean="captchaService"/>  
  91.         </property>  
  92.         <property name="captchaValidationParameter" value="j_captcha_response"/>  
  93.     </bean>  
  94.       
  95.     <!-- imageCaptchaService is injected into captchaImageCreateController as well as to captchaService beans -->  
  96.    <!--自己定义的实体类(注意路径!!)-->  
  97.     <bean id="captchaService" class="cn.hxex.order.core.jcaptcha.JCaptchaServiceProxyImpl">  
  98.         <property name="jcaptchaService" ref="imageCaptchaService"/>  
  99.     </bean>  
  100.       
  101.     <bean id="imageCaptchaService" class="com.octo.captcha.service.image.DefaultManageableImageCaptchaService">  
  102.         <constructor-arg type="com.octo.captcha.service.captchastore.CaptchaStore" index="0">  
  103.             <ref bean="fastHashMapCaptchaStore"/>  
  104.         </constructor-arg>  
  105.         <!-- (1) which captcha Engine you use -->  
  106.         <constructor-arg type="com.octo.captcha.engine.CaptchaEngine" index="1">  
  107.             <ref bean="captchaEngineEx"/>  
  108.         </constructor-arg>  
  109.         <constructor-arg index="2">  
  110.             <value>180</value>  
  111.         </constructor-arg>  
  112.         <constructor-arg index="3">  
  113.             <value>100000</value>  
  114.         </constructor-arg>  
  115.         <constructor-arg index="4">  
  116.             <value>75000</value>  
  117.         </constructor-arg>  
  118.     </bean>  
  119.   
  120.     <bean id="fastHashMapCaptchaStore" class="com.octo.captcha.service.captchastore.FastHashMapCaptchaStore"/>  
  121.   
  122.     <!-- (2) you can define more than one captcha engine here -->  
  123.     <bean id="captchaEngineEx"  
  124.           class="cn.hxex.order.core.jcaptcha.engine.CaptchaEngineEx">        
  125.     </bean>  
  126.   
  127.          <bean id="filterChainProxy"  
  128.         class="org.acegisecurity.util.FilterChainProxy">  
  129.         <property name="filterInvocationDefinitionSource">   
  130.             <value>  
  131.                 CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON  
  132.                 PATTERN_TYPE_APACHE_ANT  
  133.                 /**=httpSessionContextIntegrationFilter,captchaValidationProcessingFilter,channelProcessingFilter,authenticationProcessingFilter,exceptionTranslationFilter,filterInvocationInterceptor  
  134.             </value>  
  135.         </property>  
  136.     </bean>  
  137.   
  138.          <bean id="httpSessionContextIntegrationFilter"  
  139.         class="org.acegisecurity.context.HttpSessionContextIntegrationFilter">  
  140.         <!-- 将下面的property注释掉,验证码将无效!!! -->  
  141.         <property name="context">  
  142.             <value>  
  143.                 org.acegisecurity.captcha.CaptchaSecurityContextImpl  
  144.             </value>  
  145.         </property>  
  146.     </bean>  
  147. ·············省略了一些spring安全框架的bean,自己加去吧  



4、编写jcaptcha的实体类

实体类包的路径一定要和spring配置文件里的路径一样

(1)CaptchaEngine 类

Java代码  收藏代码
  1. package cn.hxex.order.core.jcaptcha.engine;  
  2.   
  3. import java.awt.Color;  
  4.   
  5. import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;  
  6. import com.octo.captcha.component.image.backgroundgenerator  
  7.   .FunkyBackgroundGenerator;  
  8. import com.octo.captcha.component.image.fontgenerator.FontGenerator;  
  9. import com.octo.captcha.component.image.fontgenerator  
  10.   .TwistedAndShearedRandomFontGenerator;  
  11. import com.octo.captcha.component.image.textpaster.RandomTextPaster;  
  12. import com.octo.captcha.component.image.textpaster.TextPaster;  
  13. import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage;  
  14. import com.octo.captcha.component.image.wordtoimage.WordToImage;  
  15. import com.octo.captcha.component.word.wordgenerator.RandomWordGenerator;  
  16. import com.octo.captcha.component.word.wordgenerator.WordGenerator;  
  17. import com.octo.captcha.engine.image.ListImageCaptchaEngine;  
  18. import com.octo.captcha.image.gimpy.GimpyFactory;  
  19.   
  20. /** 
  21.  * SpringSide Custom的认证图片 
  22.  *  
  23.  * @author cac 
  24.  */  
  25. public class CaptchaEngine extends ListImageCaptchaEngine {  
  26.   /** 
  27.    * @see ListImageCaptchaEngine 
  28.    */  
  29.   protected void buildInitialFactories() {  
  30.     WordGenerator wordGenerator   
  31.       = new RandomWordGenerator("023456789");  
  32.     // nteger minAcceptedWordLength, Integer maxAcceptedWordLength,Color[]  
  33.     // textColors  
  34.     TextPaster textPaster = new RandomTextPaster(4,5, Color.WHITE);  
  35.     // Integer width, Integer height  
  36.     BackgroundGenerator backgroundGenerator   
  37.       = new FunkyBackgroundGenerator(100,40);  
  38.     // Integer minFontSize, Integer maxFontSize  
  39.     FontGenerator fontGenerator = new TwistedAndShearedRandomFontGenerator(2022);  
  40.     WordToImage wordToImage = new ComposedWordToImage(fontGenerator,  
  41.         backgroundGenerator, textPaster);  
  42.     addFactory(new GimpyFactory(wordGenerator, wordToImage));  
  43.   }  
  44. }  


(2)CaptchaEngineEx 类

Java代码  收藏代码
  1. package cn.hxex.order.core.jcaptcha.engine;  
  2.   
  3. import java.awt.Color;  
  4.   
  5. import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;  
  6. import com.octo.captcha.component.image.backgroundgenerator  
  7.   .GradientBackgroundGenerator;  
  8. import com.octo.captcha.component.image.color.SingleColorGenerator;  
  9. import com.octo.captcha.component.image.fontgenerator.FontGenerator;  
  10. import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;  
  11. import com.octo.captcha.component.image.textpaster.DecoratedRandomTextPaster;  
  12. import com.octo.captcha.component.image.textpaster.TextPaster;  
  13. import com.octo.captcha.component.image.textpaster.textdecorator  
  14.   .BaffleTextDecorator;  
  15. import com.octo.captcha.component.image.textpaster.textdecorator  
  16.   .LineTextDecorator;  
  17. import com.octo.captcha.component.image.textpaster.textdecorator.TextDecorator;  
  18. import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage;  
  19. import com.octo.captcha.component.image.wordtoimage.WordToImage;  
  20. import com.octo.captcha.component.word.wordgenerator.RandomWordGenerator;  
  21. import com.octo.captcha.component.word.wordgenerator.WordGenerator;  
  22. import com.octo.captcha.engine.image.ListImageCaptchaEngine;  
  23. import com.octo.captcha.image.gimpy.GimpyFactory;  
  24.   
  25.   
  26. /** 
  27.  * Captcha增强版本 
  28.  *  
  29.  * @author david.turing@gmail.com 
  30.  * @modifyTime 21:01:52 
  31.  * @description  
  32.  * <pre> 
  33.  *  安装 Captcha Instruction <br> 
  34.  *  1.add captchaValidationProcessingFilter  
  35.  *    to applicationContext-acegi-security.xml<br> 
  36.  *  2.modify applicationContext-captcha-security.xml 
  37.  *    <ul> 
  38.  *    <li> make sure that captchaValidationProcessingFilter Call captchaService 
  39.       <li> config CaptchaEngine for captchaService (refer imageCaptchaService)  
  40.       <li> write your own CaptchaEngine 
  41.       <li> config the following, so that We use CaptchaEngineEx to generate the  
  42.           captcha image.  
  43.       </ul> 
  44.           <constructor-arg 
  45.  *              type="com.octo.captcha.engine.CaptchaEngine" index="1">  
  46.  *              <ref bean="captchaEngineEx"/gt; </constructor-arg>  
  47.  * </pre> 
  48.  */  
  49. public class CaptchaEngineEx extends ListImageCaptchaEngine {  
  50.   /** 
  51.    * ... 
  52.    */  
  53.   protected void buildInitialFactories() {  
  54.       
  55.      //Set Captcha Word Length Limitation which should not over 6       
  56.     Integer minAcceptedWordLength = new Integer(4);  
  57.     Integer maxAcceptedWordLength = new Integer(5);  
  58.     //Set up Captcha Image Size: Height and Width      
  59.     Integer imageHeight = new Integer(40);  
  60.     Integer imageWidth = new Integer(100);  
  61.       
  62.     //Set Captcha Font Size      
  63.     Integer minFontSize = new Integer(20);  
  64.     Integer maxFontSize = new Integer(22);  
  65.     //We just generate digit for captcha source char Although you can use  
  66.     //abcdefg......xyz  
  67.     WordGenerator wordGenerator   
  68.       = new RandomWordGenerator("023456789");  
  69.    
  70.      //cyt and unruledboy proved that backgroup not a factor of Security. A  
  71.      //captcha attacker won't affaid colorful backgroud, so we just use white  
  72.      //color, like google and hotmail.    
  73.     BackgroundGenerator backgroundGenerator = new GradientBackgroundGenerator(  
  74.         imageWidth, imageHeight, Color.white, Color.white);  
  75.     
  76.      //font is not helpful for security but it really increase difficultness for  
  77.      //attacker       
  78.     FontGenerator fontGenerator = new RandomFontGenerator(minFontSize,  
  79.         maxFontSize);      
  80.      // Note that our captcha color is Blue       
  81.     SingleColorGenerator scg = new SingleColorGenerator(Color.blue);  
  82.     
  83.      //decorator is very useful pretend captcha attack. we use two line text  
  84.      //decorators.  
  85.        
  86.     LineTextDecorator lineDecorator = new LineTextDecorator(1, Color.blue);  
  87.     // LineTextDecorator line_decorator2 = new LineTextDecorator(1, Color.blue);  
  88.     TextDecorator[] textdecorators = new TextDecorator[1];  
  89.   
  90.     textdecorators[0] = lineDecorator;  
  91.     // textdecorators[1] = line_decorator2;  
  92.   
  93.     TextPaster textPaster = new DecoratedRandomTextPaster(  
  94.         minAcceptedWordLength, maxAcceptedWordLength, scg,  
  95.         new TextDecorator[] { new BaffleTextDecorator(new Integer(1),  
  96.             Color.white) });  
  97.   
  98.     //ok, generate the WordToImage Object for logon service to use.  
  99.     WordToImage wordToImage = new ComposedWordToImage(  
  100.         fontGenerator, backgroundGenerator, textPaster);  
  101.     addFactory(new GimpyFactory(wordGenerator, wordToImage));  
  102.   }  
  103.   
  104. }  


(3)ImageCaptchaServlet 类

Java代码  收藏代码
  1. package cn.hxex.order.core.jcaptcha;  
  2.   
  3. import com.octo.captcha.service.CaptchaServiceException;  
  4. import com.octo.captcha.service.image.ImageCaptchaService;  
  5. import com.sun.image.codec.jpeg.JPEGCodec;  
  6. import com.sun.image.codec.jpeg.JPEGImageEncoder;  
  7. import org.apache.commons.lang.StringUtils;  
  8. import org.springframework.context.ApplicationContext;  
  9. import org.springframework.web.context.support.WebApplicationContextUtils;  
  10.   
  11. import javax.servlet.ServletConfig;  
  12. import javax.servlet.ServletException;  
  13. import javax.servlet.ServletOutputStream;  
  14. import javax.servlet.http.HttpServlet;  
  15. import javax.servlet.http.HttpServletRequest;  
  16. import javax.servlet.http.HttpServletResponse;  
  17. import java.awt.image.BufferedImage;  
  18. import java.io.ByteArrayOutputStream;  
  19. import java.io.IOException;  
  20.   
  21. /** 
  22.  * Servlet generates CAPTCHA jpeg images based on the JCAPTCHA package. It's 
  23.  * configured via spring, and requires a ImageCaptchaService bean with the 
  24.  * id=imageCaptchaService 
  25.  * 基于JCAPTCHA生成CAPTCHA jpeg图片的Servlet。它通过Spring进行配置,并且set一个 
  26.  * 类型为ImageCaptchaService,id为imageCaptchaService的bean 
  27.  * @author Jason Thrasher 
  28.  */  
  29. @SuppressWarnings("serial")  
  30. public class ImageCaptchaServlet extends HttpServlet {  
  31.   /** 
  32.    * Captcha Service Name 
  33.    */  
  34.   private String captchaServiceName = "imageCaptchaService";  
  35.   /** 
  36.    * @see HttpServlet#init(ServletConfig) 
  37.    */  
  38.   public void init(ServletConfig servletConfig) throws ServletException {  
  39.     if (StringUtils.isNotBlank(servletConfig  
  40.         .getInitParameter("captchaServiceName"))) {  
  41.       captchaServiceName = servletConfig.getInitParameter("captchaServiceName");  
  42.     }  
  43.   
  44.     super.init(servletConfig);  
  45.   }  
  46.   /** 
  47.    * @see HttpServlet#doGet() 
  48.    */  
  49.   protected void doGet(HttpServletRequest httpServletRequest,  
  50.       HttpServletResponse httpServletResponse) throws ServletException,  
  51.       IOException {  
  52.   
  53.     byte[] captchaChallengeAsJpeg = null;  
  54.     // the output stream to render the captcha image as jpeg into  
  55.     ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();  
  56.     try {  
  57.       // get the image captcha service defined via the SpringFramework  
  58.       ApplicationContext ctx = WebApplicationContextUtils  
  59.           .getRequiredWebApplicationContext(getServletContext());  
  60.       Object bean = ctx.getBean(captchaServiceName);  
  61.       ImageCaptchaService imageCaptchaService = (ImageCaptchaService) bean;  
  62.   
  63.       // get the session id that will identify the generated captcha.  
  64.       // the same id must be used to validate the response, the session id  
  65.       // is a good candidate!  
  66.       String captchaId = httpServletRequest.getSession().getId();  
  67.       // call the ImageCaptchaService getChallenge method  
  68.       BufferedImage challenge = imageCaptchaService.getImageChallengeForID(  
  69.           captchaId, httpServletRequest.getLocale());  
  70.   
  71.       // a jpeg encoder  
  72.       JPEGImageEncoder jpegEncoder = JPEGCodec  
  73.           .createJPEGEncoder(jpegOutputStream);  
  74.       jpegEncoder.encode(challenge);  
  75.     } catch (IllegalArgumentException e) {  
  76.       httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);  
  77.       return;  
  78.     } catch (CaptchaServiceException e) {  
  79.       httpServletResponse  
  80.           .sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);  
  81.       return;  
  82.     }  
  83.   
  84.     captchaChallengeAsJpeg = jpegOutputStream.toByteArray();  
  85.     // flush it in the response  
  86.     httpServletResponse.setHeader("Cache-Control""no-store");  
  87.     httpServletResponse.setHeader("Pragma""no-cache");  
  88.     httpServletResponse.setDateHeader("Expires"0);  
  89.     httpServletResponse.setContentType("image/jpeg");  
  90.     ServletOutputStream responseOutputStream = httpServletResponse  
  91.         .getOutputStream();  
  92.     responseOutputStream.write(captchaChallengeAsJpeg);  
  93.     responseOutputStream.flush();  
  94.     responseOutputStream.close();  
  95.   }  
  96. }  



(4)JCaptchaServiceProxyImpl 类

Java代码  收藏代码
  1. package cn.hxex.order.core.jcaptcha;  
  2.   
  3. import com.octo.captcha.service.CaptchaService;  
  4. import com.octo.captcha.service.CaptchaServiceException;  
  5. import org.acegisecurity.captcha.CaptchaServiceProxy;  
  6. import org.apache.commons.logging.Log;  
  7. import org.apache.commons.logging.LogFactory;  
  8.   
  9. /** 
  10.  * 实现 CaptchaServiceProxy 用于acegi来校验,由spring注入jcaptchaService 
  11.  *  
  12.  * @author sshwsfc@gmail.com 
  13.  */  
  14. public class JCaptchaServiceProxyImpl implements CaptchaServiceProxy {  
  15.   /** 
  16.    * Log for the class 
  17.    */  
  18.   protected static Log log = LogFactory.getLog(JCaptchaServiceProxyImpl.class);  
  19.   /** 
  20.    * instance of CaptchaService. 
  21.    */  
  22.   private CaptchaService jcaptchaService;  
  23.     
  24.   /** 
  25.    * @see {@link CaptchaServiceProxy#validateReponseForId(String, Object)} 
  26.    */  
  27.   public boolean validateReponseForId(String id, Object response) {  
  28.     log.debug("validating captcha response");  
  29.   
  30.     try {  
  31.       boolean isHuman = jcaptchaService.validateResponseForID(id, response)  
  32.           .booleanValue();  
  33.       if (isHuman) {  
  34.         log.debug("captcha passed");  
  35.       } else {  
  36.         log.warn("captcha failed");  
  37.       }  
  38.       return isHuman;  
  39.   
  40.     } catch (CaptchaServiceException cse) {  
  41.       // fixes known bug in JCaptcha  
  42.       log.warn("captcha validation failed due to exception", cse);  
  43.       return false;  
  44.     }  
  45.   }  
  46.   
  47.   public void setJcaptchaService(CaptchaService jcaptchaService) {  
  48.     this.jcaptchaService = jcaptchaService;  

 

转自:http://blog.csdn.net/jizhengjieing/article/details/6799261

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics