1.图像验证码的步骤
1.开发生成图形验证码的接口
2.在认证流程中加入图形验证码的校验
2.开发生成图像验证码的接口
验证码封装类:验证码的主要参数有图片,code, 以及过期时间。
package org.lilly.core.validate.code;
import java.awt.image.BufferedImage;
import java.time.LocalDateTime;
/**
* User: Mr.Wang
* Date: 2020/6/9
* 验证码包装类
*/
public class ImageCode {
/**
* 验证码图片
*/
private BufferedImage image;
/**
* 随机数验证码
*/
private String code;
/**
* 过期时间
*/
private LocalDateTime expireTime;
public ImageCode(BufferedImage image, String code, int expireIn) {
this.image = image;
this.code = code;
this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
}
public ImageCode(BufferedImage image, String code, LocalDateTime expireTime) {
this.image = image;
this.code = code;
this.expireTime = expireTime;
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public LocalDateTime getExpireTime() {
return expireTime;
}
public void setExpireTime(LocalDateTime expireTime) {
this.expireTime = expireTime;
}
public boolean isExpire() {
return LocalDateTime.now().isAfter(expireTime);
}
}
生成验证码的接口,生成的验证码后需要存放到session中,而操作session的重要类是SessionStrategy,并且通过流输出到页面上。
package org.lilly.core.validate.code;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
/**
* User: Mr.Wang
* Date: 2020/6/9
* 生成图形验证码的接口
*/
@RestController
public class ValidateCodeController {
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
private static final String SESSION_KEY = "SESSION_CODE";
@GetMapping("/code/image")
public void createImageCode(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
//1.生成图形验证码
ImageCode imageCode = generate();
//2.将图形验证码存入session中
sessionStrategy.setAttribute(new ServletWebRequest(httpRequest), SESSION_KEY, imageCode);
//3.以输出流显示到页面
ImageIO.write(imageCode.getImage(), "JPEG", httpResponse.getOutputStream());
}
private ImageCode generate() {
int width = 67;
int height = 23;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
String sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
g.dispose();
return new ImageCode(image, sRand, 60);
}
/**
* 生成随机背景条纹
*
* @param fc
* @param bc
* @return
*/
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}
3.在认证流程中加入图形验证码的校验
实现OncePerRequestFilter
package org.lilly.core.validate.code;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
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 java.io.IOException;
/**
* User: Mr.Wang
* Date: 2020/6/9
* 校验验证码的过滤器 OncePerRequestFilter 只会执行一次的过滤器
*/
public class ValidateCodeFilter extends OncePerRequestFilter {
private static final String SESSION_KEY = "SESSION_CODE";
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
private AuthenticationFailureHandler authenticationFailureHandler;
public ValidateCodeFilter(AuthenticationFailureHandler authenticationFailureHandler) {
this.authenticationFailureHandler = authenticationFailureHandler;
}
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
FilterChain filterChain) throws ServletException, IOException {
if (StringUtils.equalsIgnoreCase("/authentication/form", httpServletRequest.getRequestURI())
&& StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) { if (StringUtils.equalsIgnoreCase("/authentication/form", httpServletRequest.getRequestURI())
&& StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) {
try {
validate(httpServletRequest);
} catch (ValidateException e) {
//如果有异常,用登录失败异常处理器,这里必须处理AuthenticationException
authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
//验证码校验有异常必须要返回,不然还会去验用户名和密码。
return;
}
}
//没有异常 登录成功放行
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
private void validate(HttpServletRequest httpServletRequest) throws ServletRequestBindingException {
ImageCode imageCodeInSession = (ImageCode) sessionStrategy.getAttribute(new ServletWebRequest(httpServletRequest), SESSION_KEY);
//拿到post请求中的参数
String code = ServletRequestUtils.getStringParameter(httpServletRequest, "imageCode");
if (StringUtils.isBlank(code)) {
throw new ValidateException("验证码不能为空");
}
if (imageCodeInSession == null) {
throw new ValidateException("验证码不存在");
}
if (imageCodeInSession.isExpire()) {
sessionStrategy.removeAttribute(new ServletWebRequest(httpServletRequest), SESSION_KEY);
throw new ValidateException("验证码已过期");
}
if (!StringUtils.equals(imageCodeInSession.getCode(), code)) {
throw new ValidateException("验证码不正确");
}
sessionStrategy.removeAttribute(new ServletWebRequest(httpServletRequest), SESSION_KEY);
}
}
并且将过滤器放在UsernamePasswordAuthenticationFilter之前,失败了调用我们的失败处理。
测试:
输入正确验证码,登录成功返回用户信息