图片验证码进行认证验证码是否正确。
- CaptchaFilter
/**
* 图片验证码校验过滤器,在登录过滤器前
*/
@Slf4j
@Component
public class CaptchaFilter extends OncePerRequestFilter {
private final String loginUrl = "/login";
@Autowired
RedisUtil redisUtil;
@Autowired
LoginFailureHandler loginFailureHandler;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String url = request.getRequestURI();
if (loginUrl.equals(url) && request.getMethod().equals("POST")) {
log.info("获取到login链接,正在校验验证码 -- " + url);
try {
validate(request);
} catch (CaptchaException e) {
log.info(e.getMessage());
// 交给登录失败处理器处理
loginFailureHandler.onAuthenticationFailure(request, response, e);
}
}
filterChain.doFilter(request, response);
}
private void validate(HttpServletRequest request) {
String code = request.getParameter("code");
String token = request.getParameter("token");
if (StringUtils.isBlank(code) || StringUtils.isBlank(token)) {
throw new CaptchaException("验证码不能为空");
}
if(!code.equals(redisUtil.hget(Const.captcha_KEY, token))) {
throw new CaptchaException("验证码不正确");
}
// 一次性使用
redisUtil.hdel(Const.captcha_KEY, token);
}
}
上面代码中,因为验证码需要存储,所以添加了RedisUtil工具类,这个工具类代码我们就不贴出来了。
- com.leon.util.RedisUtil
然后验证码出错的时候我们返回异常信息,这是一个认证异常,所以我们自定了一个CaptchaException:
- com.javacat.common.exception.CaptchaException
public class CaptchaException extends AuthenticationException {
public CaptchaException(String msg) {
super(msg);
}
}
- com.leon.common.lang.Const
public class Const {
public static final String captcha_KEY = "captcha";
}
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
LoginFailureHandler loginFailureHandler;
@Autowired
CaptchaFilter captchaFilter;
public static final String[] URL_WHITELIST = {
"/webjars/**",
"/favicon.ico",
"/captcha",
"/login",
"/logout",
};
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.formLogin()
.failureHandler(loginFailureHandler)
.and()
.authorizeRequests()
.antMatchers(URL_WHITELIST).permitAll() //白名单
.anyRequest().authenticated()
// 不会创建 session
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class) // 登录验证码校验过滤器
;
}
}