ITeye博客

spring security进级篇VI JCaptcha验证编码的使用

snoopy7713 · 2012-11-28 13:10 · spring--security · 行业应用 · Spring · Security · Markdown

在spring security中,可以结合jcaptcha进行使用,具体方法如下:

1.java类如下:

Java代码  收藏代码

  1. package  com.spring.security.jcaptcha;
  2. import  java.awt.Color;
  3. import  java.awt.Font;
  4. import  java.awt.image.ImageFilter;
  5. import  com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;
  6. import  com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator;
  7. import  com.octo.captcha.component.image.color.RandomListColorGenerator;
  8. import  com.octo.captcha.component.image.deformation.ImageDeformation;
  9. import  com.octo.captcha.component.image.deformation.ImageDeformationByFilters;
  10. import  com.octo.captcha.component.image.fontgenerator.FontGenerator;
  11. import  com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;
  12. import  com.octo.captcha.component.image.textpaster.DecoratedRandomTextPaster;
  13. import  com.octo.captcha.component.image.textpaster.TextPaster;
  14. import  com.octo.captcha.component.image.textpaster.textdecorator.TextDecorator;
  15. import  com.octo.captcha.component.image.wordtoimage.DeformedComposedWordToImage;
  16. import  com.octo.captcha.component.image.wordtoimage.WordToImage;
  17. import  com.octo.captcha.component.word.FileDictionary;
  18. import  com.octo.captcha.component.word.wordgenerator.ComposeDictionaryWordGenerator;
  19. import  com.octo.captcha.component.word.wordgenerator.WordGenerator;
  20. import  com.octo.captcha.engine.image.ListImageCaptchaEngine;
  21. import  com.octo.captcha.image.gimpy.GimpyFactory;
  22. /**
  23. * JCaptcha验证码图片生成引擎, 仿照JCaptcha2.0编写类似GMail验证码的样式.
  24. */
  25. public   class  GMailEngine  extends  ListImageCaptchaEngine {
  26. @Override
  27. protected   void  buildInitialFactories() {
  28. // 图片和字体大小设置
  29. int  minWordLength =  4 ;
  30. int  maxWordLength =  5 ;
  31. int  fontSize =  20 ;
  32. int  imageWidth =  100 ;
  33. int  imageHeight =  36 ;
  34. WordGenerator dictionnaryWords = new  ComposeDictionaryWordGenerator(
  35. new  FileDictionary( "toddlist" ));
  36. // word2image components
  37. TextPaster randomPaster = new  DecoratedRandomTextPaster(minWordLength,
  38. maxWordLength, new  RandomListColorGenerator( new  Color[] {
  39. new  Color( 23 ,  170 ,  27 ),  new  Color( 220 ,  34 ,  11 ),
  40. new  Color( 23 ,  67 ,  172 ) }),  new  TextDecorator[] {});
  41. BackgroundGenerator background = new  UniColorBackgroundGenerator(
  42. imageWidth, imageHeight, Color.white);
  43. FontGenerator font = new  RandomFontGenerator(fontSize, fontSize,
  44. new  Font[] {  new  Font( "nyala" , Font.BOLD, fontSize),
  45. new  Font( "Bell MT" , Font.PLAIN, fontSize),
  46. new  Font( "Credit valley" , Font.BOLD, fontSize) });
  47. ImageDeformation postDef = new  ImageDeformationByFilters(
  48. new  ImageFilter[] {});
  49. ImageDeformation backDef = new  ImageDeformationByFilters(
  50. new  ImageFilter[] {});
  51. ImageDeformation textDef = new  ImageDeformationByFilters(
  52. new  ImageFilter[] {});
  53. WordToImage word2image = new  DeformedComposedWordToImage(font,
  54. background, randomPaster, backDef, textDef, postDef);
  55. addFactory(new  GimpyFactory(dictionnaryWords, word2image));
  56. }
  57. }

 

过滤器如下:

Java代码  收藏代码

  1. package  com.spring.security.jcaptcha;
  2. import  java.awt.image.BufferedImage;
  3. import  java.io.IOException;
  4. import  javax.imageio.ImageIO;
  5. import  javax.servlet.Filter;
  6. import  javax.servlet.FilterChain;
  7. import  javax.servlet.FilterConfig;
  8. import  javax.servlet.ServletException;
  9. import  javax.servlet.ServletOutputStream;
  10. import  javax.servlet.ServletRequest;
  11. import  javax.servlet.ServletResponse;
  12. import  javax.servlet.http.HttpServletRequest;
  13. import  javax.servlet.http.HttpServletResponse;
  14. import  org.apache.commons.lang.StringUtils;
  15. import  org.apache.log4j.Logger;
  16. import  org.springframework.context.ApplicationContext;
  17. import  org.springframework.web.context.support.WebApplicationContextUtils;
  18. import  com.octo.captcha.service.CaptchaService;
  19. import  com.octo.captcha.service.CaptchaServiceException;
  20. /**
  21. * 针对 JCaptcha 专门的过滤器(Filter)
  22. *
  23. */
  24. public   class  JCaptchaFilter  implements  Filter {
  25. // web.xml中的参数名定义
  26. public   static   final  String PARAM_CAPTCHA_PARAMTER_NAME =  "captchaParamterName" ;
  27. public   static   final  String PARAM_CAPTCHA_SERVICE_ID =  "captchaServiceId" ;
  28. public   static   final  String PARAM_FILTER_PROCESSES_URL =  "filterProcessesUrl" ;
  29. public   static   final  String PARAM_FAILURE_URL =  "failureUrl" ;
  30. public   static   final  String PARAM_AUTO_PASS_VALUE =  "autoPassValue" ;
  31. // 默认值定义
  32. public   static   final  String DEFAULT_FILTER_PROCESSES_URL =  "/j_spring_security_check" ;
  33. public   static   final  String DEFAULT_CAPTCHA_SERVICE_ID =  "captchaService" ;
  34. public   static   final  String DEFAULT_CAPTCHA_PARAMTER_NAME =  "j_captcha" ;
  35. protected   static  Logger logger = Logger.getLogger( "service" );
  36. private  String failureUrl;
  37. private  String filterProcessesUrl = DEFAULT_FILTER_PROCESSES_URL;
  38. private  String captchaServiceId = DEFAULT_CAPTCHA_SERVICE_ID;
  39. private  String captchaParamterName = DEFAULT_CAPTCHA_PARAMTER_NAME;
  40. private  String autoPassValue;
  41. private  CaptchaService captchaService;
  42. /**
  43. * Filter回调初始化函数.
  44. */
  45. public   void  init(FilterConfig filterConfig)  throws  ServletException {
  46. // TODO Auto-generated method stub
  47. initParameters(filterConfig);
  48. initCaptchaService(filterConfig);
  49. }
  50. public   void  doFilter(ServletRequest theRequest,ServletResponse theResponse, FilterChain chain)  throws  IOException,
  51. ServletException {
  52. HttpServletRequest request = (HttpServletRequest) theRequest;
  53. HttpServletResponse response = (HttpServletResponse) theResponse;
  54. String servletPath = request.getServletPath();
  55. // 符合filterProcessesUrl为验证处理请求,其余为生成验证图片请求.
  56. if  (StringUtils.startsWith(servletPath, filterProcessesUrl)) {
  57. boolean  validated = validateCaptchaChallenge(request);
  58. if  (validated) {
  59. chain.doFilter(request, response);
  60. } else  {
  61. redirectFailureUrl(request, response);
  62. }
  63. } else  {
  64. genernateCaptchaImage(request, response);
  65. }
  66. }
  67. /**
  68. * Filter回调退出函数.
  69. */
  70. public   void  destroy() {
  71. // TODO Auto-generated method stub
  72. }
  73. /**
  74. * 初始化web.xml中定义的filter init-param.
  75. */
  76. protected   void  initParameters( final  FilterConfig fConfig) {
  77. if  (StringUtils.isBlank(fConfig.getInitParameter(PARAM_FAILURE_URL))) {
  78. throw   new  IllegalArgumentException( "CaptchaFilter缺少failureUrl参数" );
  79. }
  80. failureUrl = fConfig.getInitParameter(PARAM_FAILURE_URL);
  81. if  (StringUtils.isNotBlank(fConfig
  82. .getInitParameter(PARAM_FILTER_PROCESSES_URL))) {
  83. filterProcessesUrl = fConfig
  84. .getInitParameter(PARAM_FILTER_PROCESSES_URL);
  85. }
  86. if  (StringUtils.isNotBlank(fConfig
  87. .getInitParameter(PARAM_CAPTCHA_SERVICE_ID))) {
  88. captchaServiceId = fConfig
  89. .getInitParameter(PARAM_CAPTCHA_SERVICE_ID);
  90. }
  91. if  (StringUtils.isNotBlank(fConfig
  92. .getInitParameter(PARAM_CAPTCHA_PARAMTER_NAME))) {
  93. captchaParamterName = fConfig
  94. .getInitParameter(PARAM_CAPTCHA_PARAMTER_NAME);
  95. }
  96. if  (StringUtils.isNotBlank(fConfig
  97. .getInitParameter(PARAM_AUTO_PASS_VALUE))) {
  98. autoPassValue = fConfig.getInitParameter(PARAM_AUTO_PASS_VALUE);
  99. }
  100. }
  101. /**
  102. * 从ApplicatonContext获取CaptchaService实例.
  103. */
  104. protected   void  initCaptchaService( final  FilterConfig fConfig) {
  105. ApplicationContext context = WebApplicationContextUtils
  106. .getWebApplicationContext(fConfig.getServletContext());
  107. captchaService = (CaptchaService) context.getBean(captchaServiceId);
  108. }
  109. /**
  110. * 生成验证码图片.
  111. */
  112. protected   void  genernateCaptchaImage( final  HttpServletRequest request,
  113. final  HttpServletResponse response)  throws  IOException {
  114. setDisableCacheHeader(response);
  115. response.setContentType("image/jpeg" );
  116. ServletOutputStream out = response.getOutputStream();
  117. try  {
  118. String captchaId = request.getSession(true ).getId();
  119. BufferedImage challenge = (BufferedImage) captchaService
  120. .getChallengeForID(captchaId, request.getLocale());
  121. ImageIO.write(challenge, "jpg" , out);
  122. out.flush();
  123. } catch  (CaptchaServiceException e) {
  124. logger.error(e.getMessage(), e);
  125. } finally  {
  126. if (out!= null ){
  127. out.close();
  128. }
  129. }
  130. }
  131. /**
  132. * 验证验证码.
  133. */
  134. protected   boolean  validateCaptchaChallenge( final  HttpServletRequest request) {
  135. try  {
  136. String captchaID = request.getSession().getId();
  137. String challengeResponse = request
  138. .getParameter(captchaParamterName);
  139. // 自动通过值存在时,检验输入值是否等于自动通过值
  140. if  (StringUtils.isNotBlank(autoPassValue)&& autoPassValue.equals(challengeResponse)) {
  141. return   true ;
  142. }
  143. return  captchaService.validateResponseForID(captchaID,challengeResponse);
  144. } catch  (CaptchaServiceException e) {
  145. logger.error(e.getMessage(), e);
  146. return   false ;
  147. }
  148. }
  149. /**
  150. * 跳转到失败页面.
  151. *
  152. * 可在子类进行扩展, 比如在session中放入SpringSecurity的Exception.
  153. */
  154. protected   void  redirectFailureUrl( final  HttpServletRequest request, final  HttpServletResponse response)  throws  IOException {
  155. response.sendRedirect(request.getContextPath() + failureUrl);
  156. }
  157. /**
  158. * 设置禁止客户端缓存的Header.
  159. */
  160. public   static   void  setDisableCacheHeader(HttpServletResponse response) {
  161. // Http 1.0 header
  162. response.setDateHeader("Expires" , 1L);
  163. response.addHeader("Pragma" ,  "no-cache" );
  164. // Http 1.1 header
  165. response.setHeader("Cache-Control" ,  "no-cache, no-store, max-age=0" );
  166. }
  167. }

 

web.xml 配置如下:

Xml代码  收藏代码

  1. <? xml   version = "1.0"   encoding = "UTF-8" ?>
  2. < web-app   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"   xmlns = "http://java.sun.com/xml/ns/javaee"   xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"   xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"   id = "WebApp_ID"   version = "2.5" >
  3. < display-name > springSecurityIII </ display-name >
  4. <!--******************************** -->
  5. <!--*******log4j日志信息的配置****** -->
  6. <!--******************************* -->
  7. < context-param >
  8. < param-name > log4jConfigLocation </ param-name >
  9. < param-value > classpath:log4j.xml </ param-value >
  10. </ context-param >
  11. <!--Spring默认刷新Log4j配置文件的间隔,单位为millisecond,可以不设置 -->
  12. < context-param >
  13. < param-name > log4jRefreshInterval </ param-name >
  14. < param-value > 60000 </ param-value >
  15. </ context-param >
  16. <!--******************************** -->
  17. <!--*******spring bean的配置******** -->
  18. <!--******************************* -->
  19. < context-param >
  20. < param-name > contextConfigLocation </ param-name >
  21. < param-value > classpath:applicationContext.xml </ param-value >
  22. </ context-param >
  23. < listener >
  24. < listener-class > org.springframework.web.util.Log4jConfigListener </ listener-class >
  25. </ listener >
  26. < listener >
  27. < listener-class > org.springframework.web.context.ContextLoaderListener </ listener-class >
  28. </ listener >
  29. < listener >
  30. < listener-class > org.springframework.web.util.IntrospectorCleanupListener </ listener-class >
  31. </ listener >
  32. <!--******************************** -->
  33. <!--*******字符集 过滤器************ -->
  34. <!--******************************* -->
  35. < filter >
  36. < filter-name > CharacterEncodingFilter </ filter-name >
  37. < filter-class > org.springframework.web.filter.CharacterEncodingFilter </ filter-class >
  38. < init-param >
  39. < param-name > encoding </ param-name >
  40. < param-value > UTF-8 </ param-value >
  41. </ init-param >
  42. < init-param >
  43. < param-name > forceEncoding </ param-name >
  44. < param-value > true </ param-value >
  45. </ init-param >
  46. </ filter >
  47. < filter-mapping >
  48. < filter-name > CharacterEncodingFilter </ filter-name >
  49. < url-pattern > /* </ url-pattern >
  50. </ filter-mapping >
  51. <!--******************************** -->
  52. <!--*******session的配置************ -->
  53. <!--******************************* -->
  54. < session-config >
  55. < session-timeout > 30 </ session-timeout >
  56. </ session-config >
  57. < filter >
  58. < filter-name > jcaptchaFilter </ filter-name >
  59. < filter-class > com.spring.security.jcaptcha.JCaptchaFilter </ filter-class >
  60. < init-param >
  61. < param-name > failureUrl </ param-name >
  62. < param-value > /login.jsp </ param-value >
  63. </ init-param >
  64. </ filter >
  65. < filter-mapping >
  66. < filter-name > jcaptchaFilter </ filter-name >
  67. < url-pattern > /jcaptcha.jpg </ url-pattern >
  68. </ filter-mapping >
  69. < filter-mapping >
  70. < filter-name > jcaptchaFilter </ filter-name >
  71. < url-pattern > /j_spring_security_check </ url-pattern >
  72. </ filter-mapping >
  73. < filter >
  74. < filter-name > springSecurityFilterChain </ filter-name >
  75. < filter-class > org.springframework.web.filter.DelegatingFilterProxy </ filter-class >
  76. </ filter >
  77. < filter-mapping >
  78. < filter-name > springSecurityFilterChain </ filter-name >
  79. < url-pattern > /* </ url-pattern >
  80. </ filter-mapping >
  81. < listener >
  82. < listener-class > org.springframework.security.web.session.HttpSessionEventPublisher </ listener-class >
  83. </ listener >
  84. < welcome-file-list >
  85. < welcome-file > index.jsp </ welcome-file >
  86. </ welcome-file-list >
  87. </ web-app >

 

login.jsp

 

Java代码  收藏代码

  1. <%@ include file= "/common/taglibs.jsp" %>
  2. <%@ page language="java"  contentType= "text/html; charset=UTF-8"
  3. pageEncoding="UTF-8" %>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   "http://www.w3.org/TR/html4/loose.dtd" >
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type"  content= "text/html; charset=UTF-8" >
  8. <title>登 录</title>
  9. <script type="text/javascript" >
  10. /*==============================================
  11. *   refreash the captcha to general new picture
  12. *==============================================*/
  13. function refreshCaptcha() {
  14. $('#captchaImg' ).hide().attr(
  15. 'src' ,
  16. '<c:url value="/jcaptcha.jpg"/>'  +  '?'  + Math.floor(Math.random() *  100 )).fadeIn();
  17. }
  18. </script>
  19. </head>
  20. <body>
  21. <center>
  22. <div class = "login-error" >
  23. ${sessionScope.SPRING_SECURITY_LAST_EXCEPTION.message}
  24. </div>
  25. <form action="${pageContext.request.contextPath}/j_spring_security_check"  method= "post" >
  26. <table style="width: 60%" >
  27. <tr>
  28. <td>用户名:</td>
  29. <td>
  30. <input class  =  "login-smallInput"  type= 'text'  name= 'j_username' />
  31. </td>
  32. </tr>
  33. <tr>
  34. <td>密   码:</td>
  35. <td>
  36. <input class  =  "login-smallInput"  type= 'password'  name= 'j_password'  />
  37. </td>
  38. </tr>
  39. <tr>
  40. <td>验证码:</td>
  41. <td>
  42. <input type='text'  name= 'j_captcha'  size= "5" />
  43. <img id="captchaImg"  style= "vertical-align:middle"  src= "<c:url value=" /jcaptcha.jpg "/>"  />
  44. <a href="javascript:refreshCaptcha()" >看不清楚换一张</a>
  45. </td>
  46. </tr>
  47. <tr>
  48. <td>
  49. <input id="_spring_security_remember_me"  name= "_spring_security_remember_me"  type= "checkbox" />
  50. </td>
  51. <td>
  52. <label for = "_spring_security_remember_me" >Remember Me?</label>
  53. </td>
  54. </tr>
  55. <tr>
  56. <td colspan="2" >
  57. <input type="submit"  name= "submit"  value= "登录"  />
  58. </td>
  59. </tr>
  60. </table>
  61. </form>
  62. </center>
  63. </body>
  64. </html>

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。