1.生成验证码
1.1添加hutool依赖
<!-- 验证码 --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.16</version> </dependency>
1.2创建验证码控制器
@RestController public class CaptchaController { @Value("${imgpath}") private String imgpath; // 验证码的本地路径 @Resource private RedisTemplate redisTemplate; @RequestMapping("/getcaptcha") public Object getCaptcha1(){ // 1.生成验证码到本地 //定义图形验证码的长和宽 (这个验证码的大小需要和自己前端的验证码的大小匹配) LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(128, 50); String uuid = UUID.randomUUID().toString().replace("-",""); // 图形验证码写出,可以写出到文件,也可以写出到流 lineCaptcha.write(imgpath + uuid + ".png"); String url = "/image/"+uuid+".png"; // 将验证码存储到 redis redisTemplate.opsForValue().set(uuid,lineCaptcha.getCode(),5, TimeUnit.MINUTES); HashMap<String,String > result = new HashMap<>(); result.put("codeurl",url); result.put("codekey",uuid); return Result.successmap(result); } }
1.3修改配置文件yaml(这里添加的是本地路径)
imgpath: D:/SpringBoot/tiantianxitong/codeImg/
1.4前端代码
<div class="row" style="margin-bottom: 20px;"> <input id="checkCode" style="width: 110px;margin-left: 15px" v-model="user.code" placeholder="输入验证码"/> <input style="width: 76px;margin-left: 15px;display: none" name="codekey" v-model="user.codekey" placeholder="验证码key"/> <img οnclick="loadCode()" id="codeimg":src="'http://localhost:1900'+captcode.codeurl" style="height: 50px;width: 128px;"> </div>
访问http://localhost:1900/getcaptcha
2. 将本地验证码发布成 URL
2.1配置映射路径
@Configuration public class AppConfig implements WebMvcConfigurer { @Value("${imgpath}") private String imgpath; /** * 映射图片路径 * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/image/**") .addResourceLocations("file:" + imgpath + "/"); } }
这里注意要在securitycinfig里放行image/** 和 /getcaptcha
public static final String[] URL_LIST={ "/login", "/logout", "/getcaptcha", "/image/**", };
2.2 使用映射后的网络路径访问验证码
成功访问!!!
3.在登录成功LoginSuccessHandler里判断验证码
@SneakyThrows @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { response.setContentType("application/json;charset=UTF-8"); ServletOutputStream outputStream = response.getOutputStream(); String name = authentication.getName(); Our our = ourMapper.queryUser(name); String token = JWTUtils.getToken(name); //接收验证码进行判断 String code = request.getParameter("code"); String codeKey = request.getParameter("codekey"); System.out.println("code=="+code); System.out.println("codekey=="+codeKey); if (codeKey==null){ throw new Exception("验证码key为空"); } String codevalue = (String) redisTemplate.opsForValue().get(codeKey); System.out.println("这里的codevalue=="+codevalue); if (StrUtil.isEmpty(codevalue)){ try { outputStream.write(JSONUtil.toJsonStr(Result.success("redis验证码为空").put("code",-2)).getBytes(StandardCharsets.UTF_8)); outputStream.flush(); outputStream.close(); return; } catch (Exception e) { e.printStackTrace(); } } if (!code.equals(codevalue)){ try { outputStream.write(JSONUtil.toJsonStr(Result.success("验证码不正确").put("code",-3)).getBytes(StandardCharsets.UTF_8)); outputStream.flush(); outputStream.close(); return; } catch (Exception e) { e.printStackTrace(); } } outputStream.write(JSONUtil.toJsonStr(Result.success("登录成功").put("user",our).put("token",token)).getBytes(StandardCharsets.UTF_8)); outputStream.flush(); outputStream.close(); }
判断验证码不只有这一种方法,也可以在过滤器里进行判断可以网上参看其他人在过滤验证码判断,这里是我在代码学习自己编写的一种方法!!!!