Spring Security添加验证码的两种方式小结

网友投稿 239 2022-12-03

Spring Security添加验证码的两种方式小结

目录一、自定义认证逻辑二、自定义过滤器总结

一、自定义认证逻辑

生成验证码工具

com.github.penggle

kaptcha

2.3.2

添加Kaptcha配置

@Configuration

public class KaptchaConfig {

@Bean

Producer kaptcha() {

Properties properties = new Properties();

properties.setProperty("kaptcha.image.width", "150");

properties.setProperty("kaptcha.image.height", "50");

properties.setProperty("kaptcha.textproducer.char.string", "0123456789");

properties.setProperty("kaptcha.textproducer.char.length", "4");

Config config = new Config(properties);

DefaultKaptcha defaultKaptcha = new DefaultKaptcha();

defaultKaptcha.setConfig(config);

return defaultKaptcha;

}

}

生成验证码文本,放入HttpSession中

根据验证码文本生成图片 通过IO流写出到前端。

@RestController

public class LoginController {

@Autowired

Producer producer;

@GetMapping("/vc.jpg")

public void getVerifyCode(HttpServletResponse resp, HttpSession session) throws IOException {

resp.setContentType("image/jpeg");

String text = producer.createText();

session.setAttribute("kaptchaQtYbZr", text);

BufferedImage image = producer.createImage(text);

try(ServletOutputStream out = resp.getOutputStream()) {

ImageIO.write(image, "jpg", out);

}

}

@RequestMapping("/index")

public String index() {

return "login success";

}

@RequestMapping("/hello")

public String hello() {

return "hello spring security";

}

}

form表单