【问题标题】:How do integrate kaptcha in java spring如何在java spring中集成验证码
【发布时间】:2019-03-05 06:05:38
【问题描述】:

我需要在java spring中集成kaptcha,官网https://code.google.com/p/kaptcha/wiki/SpringUsage是很老的资​​料了。

【问题讨论】:

    标签: java spring captcha


    【解决方案1】:
    1. 添加maven依赖:

      <dependency>
          <groupId>com.github.penggle</groupId>
          <artifactId>kaptcha</artifactId>
          <version>2.3.2</version>
      </dependency>
      
    2. 将 kaptcha 配置添加到 application.properties:

      #Kaptcha 
      kaptcha.config.imageWidth=310
      kaptcha.config.imageHeight=55
      kaptcha.config.textProducerCharString=0123456789aAbBcCdDEeFeGgHhIi
      kaptcha.config.textProducerCharLength=6
      kaptcha.config.headerName=KAPTCHA_HEADER
      kaptcha.config.useBorder=no            
      kaptcha.config.textColor=48,101,137
      
    3. 使用@ConfigurationProperties 获取配置

      @Data
      @Component
      @ConfigurationProperties(prefix="kaptcha.config")
      public class KaptchaConfigurations{
      private String imageWidth;
      private String imageHeight; 
      private String textProducerCharString;
      private String textProducerCharLength;
      private String headerName;
      private String useBorder;
      private String backgroundClass;
      private String textColor;
      }
      

    *如果您不使用 lombok,请将 @Data 替换为 getter 和 setter。

    1. 声明生产者@Bean:

      @Bean 
      public Producer createKaptchaProducer(KaptchaConfigurations 
      kaptchaConfigurations) {
      DefaultKaptcha kaptcha = new DefaultKaptcha();
      Properties properties = new Properties();
      properties.put(Constants.KAPTCHA_IMAGE_HEIGHT , 
      kaptchaConfigurations.getImageHeight());
      properties.put(Constants.KAPTCHA_IMAGE_WIDTH, 
      kaptchaConfigurations.getImageWidth());
      properties.put(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH , 
      kaptchaConfigurations.getTextProducerCharLength());
      properties.put(Constants.KAPTCHA_TEXTPRODUCER_CHAR_STRING, 
      kaptchaConfigurations.getTextProducerCharString());
      properties.put(Constants.KAPTCHA_BORDER, 
      kaptchaConfigurations.getUseBorder());
      properties.put(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR,
      kaptchaConfigurations.getTextColor());
      properties.put(Constants.KAPTCHA_NOISE_COLOR,
      kaptchaConfigurations.getTextColor());
      kaptcha.setConfig(new Config(properties));
      return kaptcha;
      }
      
    2. 创建一个端点以获取生成的验证码并将验证码文本保存在会话中:

      @GetMapping("/image")
      public void handleRequest(
          HttpServletRequest request,
          HttpServletResponse response) throws Exception {
      response.setDateHeader("Expires", 0);       
      response.setHeader("Cache-Control", 
      "no-store, no-cache, must-        revalidate");     
      response.addHeader("Cache-Control", "post-check=0, pre-check=0");       
      response.setHeader("Pragma", "no-cache");       
      response.setContentType("image/jpeg");
      String capText = captchaProducer.createText();
      request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,     
      capText);
      
      // create the image with the text
      BufferedImage bi = captchaProducer.createImage(capText);
      
      ServletOutputStream out = response.getOutputStream();
      
      // write the data out
      ImageIO.write(bi, "jpg", out);
      try {
          out.flush();
      } finally {
          out.close();
      }
      }
      
    3. 创建一个方面来验证验证码:

      @Aspect
      @Component
      public class KaptchaAspect {
      
          private KaptchaConfigurations kaptchaConfigurations;
      
          public KaptchaAspect(KaptchaConfigurations kaptchaConfigurations) {
              this.kaptchaConfigurations = kaptchaConfigurations;
          }
      
          @Before("@annotation(ValidateKaptcha)")
          public void validateKaptcha() throws Throwable {         
               String headerName = this.kaptchaConfigurations.getHeaderName();
               HttpServletRequest request =
               ((ServletRequestAttributes)                                                     
               RequestContextHolder
               .currentRequestAttributes())
               .getRequest();
               String headerValue = request.getHeader(headerName);
               String kaptchaSessionValue =     
               request.getSession()
              .getAttribute(Constants.KAPTCHA_SESSION_KEY)
              .toString();
      
             if(headerValue == null || kaptchaSessionValue == null) {          
                 throw new BusinessException();
             }
      
             if(!headerValue.equals(kaptchaSessionValue)) {           
                throw new BusinessException();
             }
          }
      }
      
    4. 声明验证注解:

      import java.lang.annotation.ElementType;
      import java.lang.annotation.Retention;
      import java.lang.annotation.RetentionPolicy;
      import java.lang.annotation.Target;
      
      @Target(ElementType.METHOD)
      @Retention(RetentionPolicy.RUNTIME)
      public @interface ValidateKaptcha {
      }
      
    5. 在任何需要验证验证码的端点上使用@ValidateKaptcha:

      @ValidateKaptcha
      @PostMapping("/forgot-password-by-user-name")
      public ResponseEntity<?> forgotPasswordByUsername(@RequestBody @Valid 
             ForgotPasswordByUsernameInput forgotPasswordByUsernameInput) { 
       ...
      }
      

    从客户端传递标头中的 kaptcha 值,将其命名为 KAPTCHA_HEADER。

    【讨论】:

      【解决方案2】:

      你可以使用 reCAPTCHA ,按照这个教程它会帮助你reCAPTCHA link

      【讨论】:

      • 我不能用 recaptcha ,我用的是 katpcha,这就是问题所在。
      【解决方案3】:

      有一个开源 Spring Boot 启动项目可以为您验证 reCAPTCHA。

      您只需在配置文件中设置所需的 URL(您想使用验证码保护,例如:/api/sign-up),此库将检查用户是否发送了有效的验证码响应。

      GitHub 上的更多信息:https://github.com/Mr-DeWitt/spring-boot-recaptcha

      【讨论】:

        猜你喜欢
        • 2010-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多