SpringBoot Security 整合登录页面验证码

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"/>&nbsp;&nbsp;&nbsp;
  <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();
}

判断验证码不只有这一种方法,也可以在过滤器里进行判断可以网上参看其他人在过滤验证码判断,这里是我在代码学习自己编写的一种方法!!!!

  • 49
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值