Combined with open-source software kaptcha explain login authentication code function to achieve

file

A verification code generator configured to use the kaptcha

Google using open source codes implemented library kaptcha, incorporated by coordinates maven

<dependency>
   <groupId>com.github.penggle</groupId>
   <artifactId>kaptcha</artifactId>
   <version>2.3.2</version>
   <exclusions>
      <exclusion>
         <artifactId>javax.servlet-api</artifactId>
         <groupId>javax.servlet</groupId>
      </exclusion>
   </exclusions>
</dependency>
  • We assume that the configuration file is application.yml, create a separate file called kaptcha.properties. Because kaptcha configuration yaml non-compliant format, so only use properties. Must comply with the notes PropertySourc use.
  • We assume that the profile is application.properties, the following code to join in, without establishing a separate file.
  • The following code configuration, it is easy to understand from the perspective of English words, when we need to adjust the border verification code, color, size, font and other attributes, you can modify these configurations.
kaptcha.border=no
kaptcha.border.color=105,179,90
kaptcha.image.width=100
kaptcha.image.height=45
kaptcha.session.key=code
kaptcha.textproducer.font.color=blue
kaptcha.textproducer.font.size=35
kaptcha.textproducer.char.length=4
kaptcha.textproducer.font.names=宋体,楷体,微软雅黑

The following code is loaded kaptcha configuration (see Configuration Spring Boot Load) configuration file, if it is a separate file properties, coupled with the need PropertySource explanatory notes.
Further, we accomplished by loading the configuration, the initialization captchaProducer Spring Bean, for generating a verification code.

@Component
@PropertySource(value = {"classpath:kaptcha.properties"})
public class CaptchaConfig {

    @Value("${kaptcha.border}")
    private String border;
    @Value("${kaptcha.border.color}")
    private String borderColor;
    @Value("${kaptcha.textproducer.font.color}")
    private String fontColor;
    @Value("${kaptcha.image.width}")
    private String imageWidth;
    @Value("${kaptcha.image.height}")
    private String imageHeight;
    @Value("${kaptcha.session.key}")
    private String sessionKey;
    @Value("${kaptcha.textproducer.char.length}")
    private String charLength;
    @Value("${kaptcha.textproducer.font.names}")
    private String fontNames;
    @Value("${kaptcha.textproducer.font.size}")
    private String fontSize;

    @Bean(name = "captchaProducer")
    public DefaultKaptcha getKaptchaBean() {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", border);
        properties.setProperty("kaptcha.border.color", borderColor);
        properties.setProperty("kaptcha.textproducer.font.color", fontColor);
        properties.setProperty("kaptcha.image.width", imageWidth);
        properties.setProperty("kaptcha.image.height", imageHeight);
        properties.setProperty("kaptcha.session.key", sessionKey);
        properties.setProperty("kaptcha.textproducer.char.length", charLength);
        properties.setProperty("kaptcha.textproducer.font.names", fontNames);
        properties.setProperty("kaptcha.textproducer.font.size",fontSize);
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

}

At this point, the configuration Kaptcha open source code software we have done, if we find the configuration file to read Chinese garbled under IDEA environment, modify the following configuration.

Second, the generation of the authentication code stored session

Controller generates a verification code. At the same time need to open the path "/ kaptcha" access rights configured without login does not need any permission to access the path. How to configure the previous article I have already spoken.

  • By captchaProducer.createText () to generate verification code words, and saving time and failure to CaptchaImageVO together.
  • The class object CaptchaImageVO information codes stored in the session. (Hereinafter this class codes with a)
  • Codes generated by the image captchaProducer.createImage (capText), and returns to the front end by ServletOutputStream
@RestController
public class CaptchaController {

    @Resource
    DefaultKaptcha captchaProducer;

    /**
     * 获取验证码
     */
    @RequestMapping(value = "/kaptcha", method = RequestMethod.GET)
    public void kaptcha(HttpSession session, 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();
        CaptchaImageVO captchaImageVO = new CaptchaImageVO(capText,2 * 60);
        //将验证码存到session
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, captchaImageVO);

        //将图片返回给前端
        try(ServletOutputStream out = response.getOutputStream();) {
            BufferedImage bi = captchaProducer.createImage(capText);
            ImageIO.write(bi, "jpg", out);
            out.flush();
        }//使用try-with-resources不用手动关闭流
    }

}

We want to save CaptchaImageVO session inside. So in this class do not add pictures, text only save the verification code and expiry time for subsequent verification can be. The CAPTCHA image saved both useless and a waste of memory.

@Data
public class CaptchaImageVO {

    //验证码文字
    private String code;
    //验证码失效时间
    private LocalDateTime expireTime;
 
    public CaptchaImageVO(String code, int expireAfterSeconds){
        this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(expireAfterSeconds);
    }
 
    //验证码是否失效
    public boolean isExpried() {
        return LocalDateTime.now().isAfter(expireTime);
    }
 
}

Third, user access code

The following code is added to the login page the right place, pay attention to the picture img tag into the login form.

<img src="/kaptcha" id="kaptcha" width="110px" height="40px"/>

<script>
    window.onload=function(){
        var kaptchaImg = document.getElementById("kaptcha");
        kaptchaImg.onclick = function(){
            kaptchaImg.src = "/kaptcha?" + Math.floor(Math.random() * 100)
        }
    }
</script>
  • The effect achieved is that the page that is loaded initialization code. After each click, updated verification code.
  • Note: Be sure to set the width and height, otherwise the picture can not be displayed.

Fourth, the verification of the security check code

  • We write custom authentication code filter VerificationCodeFilter, the filter intercepts the login request
  • VerificationCodeFilter filter acquires character codes from the user input matching seesion, other than by performing filter chain
  • Not by comparison, a custom exception handling to AuthenticationFailureHandler
  • Finally VerificationCodeFilter on implementation before UsernamePasswordAuthenticationFilter Form Filler.

The above is achieved login authentication code validation logic in Spring Security. If you are using shiro or other custom login authentication to achieve, it's even easier. They were removed your login authentication session controller which codes match, you do not need custom filter.

Look forward to your attention

Guess you like

Origin www.cnblogs.com/zimug/p/11957255.html