SpringBoot整合Spring Security,使用Session方式的验证码(六)

简介: 这里用到了一个常量类,到时候做验证码判断时用的比较多:

一、导入验证码库的依赖

        <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>


二、然后写一个kaptcha.properties配置文件:

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=宋体,楷体,微软雅黑


需要注意的是这里的中文可能是乱码,改下文件格式即可:

20200923153311828.png


三、配置验证码生成类

package com.example.securityzimug.config.auth.imagecode;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import java.util.Properties;
/**
 * @author baikunlong
 * @date 2020/9/23 15:34
 */
@Configuration
@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
    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);
        defaultKaptcha.setConfig(new Config(properties));
        return defaultKaptcha;
    }
}


四、编写验证码vo

package com.example.securityzimug.config.auth.imagecode;
import java.time.LocalDateTime;
public class CaptchaCode {
    /**
     * 验证码
     */
    private String code;
    /**
     * 过期时间
     */
    private LocalDateTime expireTime;
    public CaptchaCode(String code, int expireAfterSeconds){
        this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(expireAfterSeconds);
    }
    /**
     * 是否过期
     * @return
     */
    public boolean isExpired(){
        return  LocalDateTime.now().isAfter(expireTime);
    }
    public String getCode() {
        return code;
    }
}


五、编写控制器

package com.example.securityzimug.controller;
import com.example.securityzimug.config.auth.imagecode.CaptchaCode;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
@RestController
public class CaptchaController {
    @Resource
    DefaultKaptcha captchaProducer;
    @RequestMapping(value="/kaptcha",method = RequestMethod.GET)
    public void kaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        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();
        session.setAttribute(MyContants.CAPTCHA_SESSION_KEY,new CaptchaCode(capText,60));
        try(ServletOutputStream out = response.getOutputStream()){
            BufferedImage bufferedImage = captchaProducer.createImage(capText);
            ImageIO.write(bufferedImage,"jpg",out);
            out.flush();
        }
    }
}


这里用到了一个常量类,到时候做验证码判断时用的比较多:

package com.example.securityzimug.utils;
public class MyContants {
    public static final String CAPTCHA_SESSION_KEY = "captcha_key";
    public static final String SMS_SESSION_KEY = "sms_key";
}


六、开放验证码接口权限

20200923155708521.png


七、修改登录页

<form action="/login" method="post">
    <span>用户名称</span><input type="text" name="uname" id="username"/> <br>
    <span>用户密码</span><input type="password" name="pword" id="password"/> <br>
    <span>验证码</span><input type="text" name="captchaCode" id="captchaCode"/>
    <img src="/kaptcha" id="kaptcha" width="110px" height="40px"/> <br>
    <input type="button" onclick="login()" value="登陆">
<!--    <input type="submit" value="登陆">-->
    <label><input type="checkbox" name="remember-me" id="remember-me"/>记住密码</label>
</form>


编写点击验证码刷新

    window.onload = function () {
        var kaptchaImg = document.getElementById("kaptcha");
        kaptchaImg.onclick = function () {
            kaptchaImg.src = "/kaptcha?" + Math.floor(Math.random() * 100)
        }
    };


到这里我们已经实现了验证码的刷新了:

20200923161619483.png


八、编写验证码过滤器

package com.example.securityzimug.config.auth.imagecode;
import com.example.securityzimug.config.auth.MyAuthenticationFailureHandler;
import com.example.securityzimug.utils.MyContants;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @author baikunlong
 * @date 2020/9/23 16:17
 */
@Component
public class CaptchaCodeFilter extends OncePerRequestFilter {
    @Resource
    MyAuthenticationFailureHandler myAuthenticationFailureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if("/login".equals(request.getRequestURI())&&request.getMethod().equalsIgnoreCase("post")){
            try {
                validate(request);
            } catch (AuthenticationException e) {
                //交给自定义处理器处理
                myAuthenticationFailureHandler.onAuthenticationFailure(request,httpServletResponse,e);
                //直接返回,过滤器链不再往下执行
                return;
            }
        }
        filterChain.doFilter(request,httpServletResponse);
    }
    private void validate(HttpServletRequest request) {
        //用户输入的验证码
        String captchaInRequest = request.getParameter("captchaCode");
        //session里的验证码对象
        CaptchaCode captchaInSession = (CaptchaCode) request.getSession().getAttribute(MyContants.CAPTCHA_SESSION_KEY);
        if(StringUtils.isEmpty(captchaInRequest)){
            throw new SessionAuthenticationException("验证码不能为空");
        }
        if(captchaInSession==null){
            throw new SessionAuthenticationException("验证码不存在");
        }
        if(captchaInSession.isExpired()){
            request.getSession().removeAttribute(MyContants.CAPTCHA_SESSION_KEY);
            throw new SessionAuthenticationException("验证码已经过期");
        }
        if(!captchaInSession.getCode().equalsIgnoreCase(captchaInRequest)){
            throw new SessionAuthenticationException("验证码错误");
        }
    }
}


然后在自定义的那个失败处理器里处理下验证码错误的信息

image.png



然后在配置类里注入过滤器:

    @Resource
    CaptchaCodeFilter captchaCodeFilter;


然后配置过滤器执行顺序:

        //配置验证码过滤器执行时间,设置在用户名密码校验之前
        http.addFilterBefore(captchaCodeFilter, UsernamePasswordAuthenticationFilter.class);


最后在登录页面加入验证码的提交就行了:

    function login() {
        var username = $("#username").val();
        var password = $("#password").val();
        var captchaCode = $("#captchaCode").val();
        var rememberMe = $("#remember-me").is(":checked");
        if (username === "" || password === "") {
            alert('用户名或密码不能为空');
            return;
        }
        $.ajax({
            type: "POST",
            url: "/login",
            data: {
                "uname": username,
                "pword": password,
                "captchaCode": captchaCode,
                "remember-me-new": rememberMe
            },
            success: function (json) {
                if(json.isok){
                    location.href = json.data;
                }else{
                    alert(json.message)
                }
            },
            error: function (e) {
                console.log(e.responseText);
            }
        });
    }


目录
相关文章
|
前端开发 Java 应用服务中间件
《深入理解Spring》 Spring Boot——约定优于配置的革命者
Spring Boot基于“约定优于配置”理念,通过自动配置、起步依赖、嵌入式容器和Actuator四大特性,简化Spring应用的开发与部署,提升效率,降低门槛,成为现代Java开发的事实标准。
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
1065 2
|
人工智能 Java 机器人
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
Spring AI Alibaba集成Ollama,基于Java构建本地大模型应用,支持流式对话、knife4j接口可视化,实现高隐私、免API密钥的离线AI服务。
8070 2
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
存储 JSON Java
1200 0
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
3241 0
|
Java 测试技术 数据库连接
【SpringBoot(四)】还不懂文件上传?JUnit使用?本文带你了解SpringBoot的文件上传、异常处理、组件注入等知识!并且带你领悟JUnit单元测试的使用!
Spring专栏第四章,本文带你上手 SpringBoot 的文件上传、异常处理、组件注入等功能 并且为你演示Junit5的基础上手体验
1330 3
|
JavaScript Java Maven
【SpringBoot(二)】带你认识Yaml配置文件类型、SpringMVC的资源访问路径 和 静态资源配置的原理!
SpringBoot专栏第二章,从本章开始正式进入SpringBoot的WEB阶段开发,本章先带你认识yaml配置文件和资源的路径配置原理,以方便在后面的文章中打下基础
823 4