SpringSecurity--使用过滤器实现图形验证码

<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>
package com.zcw.demospringsecurity.demo5;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import sun.security.krb5.KrbException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;

/**
 * @ClassName : CaptchaController
 * @Description : 获取图形验证码
 * @Author : Zhaocunwei
 * @Date: 2020-04-10 19:15
 */
@Controller
public class CaptchaController {

    @Autowired
    private Producer producer;

    @GetMapping("/captcha.jpg")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException{
        //设置内容类型:
        response.setContentType("image/jpeg");
        //创建验证码文本
        String textStr = producer.createText();
        //将验证码文本设置到session
        request.getSession().setAttribute("captcha",textStr);
        //创建验证码图片
        BufferedImage bufferedImage = producer.createImage(textStr);
        //获取响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //将图片验证码数据写到响应输出流
        ImageIO.write(bufferedImage,"jpg",outputStream);
        outputStream.flush();
        outputStream.close();
    }


    //TODO 后期可以移走,临时演示
    @Bean
    public Producer captcha() throws KrbException {
        //配置图形验证码的基本参数
        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;
    }
}

package com.zcw.demospringsecurity.demo5;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName : MyAuthenticationFailureHandler
 * @Description :
 * @Author : Zhaocunwei
 * @Date: 2020-04-10 20:07
 */
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse, AuthenticationException e)
            throws IOException, ServletException {

    }
}

package com.zcw.demospringsecurity.demo5;

import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName : MyVerificationCodeFilter
 * @Description : 校验验证码过滤器
 * @Author : Zhaocunwei
 * @Date: 2020-04-10 20:02
 */
public class MyVerificationCodeFilter extends OncePerRequestFilter {

    private AuthenticationFailureHandler authenticationFailureHandler = new  MyAuthenticationFailureHandler();

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
            //非登录请求不校验验证码
        if(!"/form".equals(httpServletRequest.getRequestURI())){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        }else{

        }
    }
    public void verificationCode(HttpServletRequest httpServletRequest) throws VerificationCodeException{
        String requestCode = httpServletRequest.getParameter("captcha");
        HttpSession session = httpServletRequest.getSession();
        String saveDCode =(String) session.getAttribute("captcha");
        if(!StringUtils.isEmpty(saveDCode)){
            //清除验证码,无论是成功还是失败,客户端应在登录失败时刷新验证码
            session.removeAttribute("captcha");
        }
        //校验不通过,抛出异常
        if(StringUtils.isEmpty(requestCode) || StringUtils.isEmpty(saveDCode) || !requestCode.equals(saveDCode)){
            throw new VerificationCodeException();
        }
    }
}

package com.zcw.demospringsecurity.demo5;

import javax.naming.AuthenticationException;

/**
 * @ClassName : VerificationCodeException
 * @Description : 验证码校验失败异常类
 * @Author : Zhaocunwei
 * @Date: 2020-04-10 20:01
 */
public class VerificationCodeException extends AuthenticationException {
    public VerificationCodeException(){
        super("验证码校验失败");
    }
}

发布了458 篇原创文章 · 获赞 15 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_32370913/article/details/105552212