登入驗證碼圖片
阿新 • • 發佈:2022-05-26
<!--驗證碼--> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
@Bean public DefaultKaptcha getDefaultKaptcha() { DefaultKaptcha captchaProducer= new DefaultKaptcha(); Properties properties = new Properties(); properties.setProperty("kaptcha.border", "yes"); properties.setProperty("kaptcha.border.color", "105,179,90"); properties.setProperty("kaptcha.textproducer.font.color", "blue"); properties.setProperty("kaptcha.image.width", "220"); properties.setProperty("kaptcha.image.height", "80"); properties.setProperty("kaptcha.textproducer.font.size", "40"); properties.setProperty("kaptcha.session.key", "code"); properties.setProperty("kaptcha.textproducer.char.length", "4"); properties.setProperty("kaptcha.textproducer.font.names", "宋體,楷體,微軟雅⿊"); Config config = new Config(properties); captchaProducer.setConfig(config); return captchaProducer; }
@Autowired private Producer captchaProducer; @PostMapping("/kaptcha") @ApiOperation("獲取驗證碼") @Authenticated(false) public RestResult getKaptchaImage(@RequestBody KaptchaVO vo) throws Exception { StringUtils.isTrueReMsg(vo.getImei()==null,"引數不正確"); //⽣成驗證碼 String capText = captchaProducer.createText(); redisTemplate.opsForValue().set("imei-kaptcha:"+vo.getImei(),capText); //向客戶端寫出 BufferedImage bi = captchaProducer.createImage(capText); ByteArrayOutputStream stream = new ByteArrayOutputStream(); ImageIO.write(bi, "jpg", stream); String s = Base64.getEncoder().encodeToString(stream.toByteArray()); return RestResult.successData("data:image/jpg;base64,"+s); }
//獲取⽣成的驗證碼 String verifyCodeExpected=null; Object o1 = redisTemplate.opsForValue().get("imei-kaptcha:" + request.getHeader("imei")); if(o1!=null){ verifyCodeExpected=o1.toString(); } String code = loginFormVO.getCode(); StringUtils.isTrueReMsg(code == null || !code.equals(verifyCodeExpected),"驗證碼錯誤");
說明:將生成的驗證碼存放在redis,生成驗證碼圖片base64給前端展示,登入介面加上驗證碼引數,進行比對
搜尋
複製