1 创建验证码包装类
@Data
public class ImageCode {
private BufferedImage image;
private String code;
private LocalDateTime expireTime;
public ImageCode(BufferedImage image, String code, LocalDateTime expireTime) {
this.image = image;
this.code = code;
this.expireTime = expireTime;
}
public ImageCode(BufferedImage image, String code, int expireInSeconds) {
this.image = image;
this.code = code;
this.expireTime = LocalDateTime.now().plusSeconds(expireInSeconds);
}
}
2 验证码生成逻辑
@RestController
public class ValidateCodeController {
private static final String SESSION_KEY_IMAGE_CODE = "SESSION_KEY_IMAGE_CODE";
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@GetMapping(value = "/code/image")
public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
ImageCode imageCode = crateImageCode(request);
// 存入session
sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY_IMAGE_CODE,imageCode);
ImageIO.write(imageCode.getImage(),"JPEG",response.getOutputStream());
}
private ImageCode crateImageCode(HttpServletRequest request) {
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,300);
}
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 取消获取验证码接口的拦截
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() // 表单验证
.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form") // 配置表单提交请求,此请求会被UsernamePasswordAuthenticationFilter 拦截处理
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
.and()
.authorizeRequests()
.antMatchers("/authentication/require",
properties.getBrowser().getLoginPage(),
"/code/image").permitAll() // 放行登录页、验证码获取
.anyRequest()
.authenticated() // 认证拦截所有请求
.and()
.csrf().disable(); // 关闭跨站请求拦截
}
4 登录表单新增验证码逻辑
<input type="text" class="form-control" name="validateCode" placeholder="请输入验证码" required>
<img src="/code/image">
5 自定义过滤器拦截登录请求并对验证码进行校验
public class ValidateCodeFilter extends OncePerRequestFilter {
@Setter
private AuthenticationFailureHandler authenticationFailureHandler;
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain)
throws ServletException, IOException {
if(StringUtils.equals("/authentication/form",httpServletRequest.getRequestURI())
&& StringUtils.endsWithIgnoreCase(httpServletRequest.getMethod(),"POST")){
try{
validate(new ServletWebRequest(httpServletRequest));
}catch (ValidateCodeException e){
authenticationFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
return;
}
}
filterChain.doFilter(httpServletRequest,httpServletResponse);
}
private void validate(ServletWebRequest request) throws ServletRequestBindingException {
// 获取session中的验证码
ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(request, ValidateCodeController.SESSION_KEY_IMAGE_CODE);
String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),"validateCode");
if(StringUtils.isBlank(codeInRequest)){
throw new ValidateCodeException("验证码的值不能为空");
}
if(codeInSession == null || codeInSession.isExpried()){
throw new ValidateCodeException("验证码已过期");
}
if(!StringUtils.equals(codeInRequest,codeInSession.getCode())){
throw new ValidateCodeException("验证码错误");
}
sessionStrategy.removeAttribute(request,ValidateCodeController.SESSION_KEY_IMAGE_CODE);
}
}
6 配置过滤器
@Override
protected void configure(HttpSecurity http) throws Exception {
ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
validateCodeFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
// 配置验证码过滤器,使之在登录过滤器之前生效
http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
.formLogin() // 表单验证
.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form") // 配置表单提交请求,此请求会被UsernamePasswordAuthenticationFilter 拦截处理
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
.and()
.authorizeRequests()
.antMatchers("/authentication/require",
properties.getBrowser().getLoginPage(),
"/code/image").permitAll() // 放行登录页、验证码获取
.anyRequest()
.authenticated() // 认证拦截所有请求
.and()
.csrf().disable(); // 关闭跨站请求拦截
}
打开App,阅读手记
热门评论
为什么我addFilterBefore之后访问任何请求页面都是空白