http.addFilterBefore(imageCodeValidateFilter, UsernamePasswordAuthenticationFilter.class) 将验证码过滤器链添加到用户过滤器之前。
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
/**
- 验证码过滤器
*/
@Autowired
private ImageCodeValidateFilter imageCodeValidateFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
// 验证码过滤器
http.addFilterBefore(imageCodeValidateFilter, UsernamePasswordAuthenticationFilter.class)
// 跳转前台的地址
.formLogin().loginPage(“/loginPage”)
// 登录调用的接口地址
.loginProcessingUrl(“/login”).successHandler(customAuthenticationSuccessHandler);
}
}
ImageCodeValidateFilter
验证码过滤器
@Component(“imageCodeValidateFilter”)
public class ImageCodeValidateFilter extends OncePerRequestFilter {
@Autowired
SecurityProperties securityProperties;
@Autowired
CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
@Override
protected void doFilterInternal(HttpServletRequest req 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 uest, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// 1. 如果是post方式 的登录请求,则校验输入的验证码是否正确
if (“/login”.equals(request.getRequestURI()) && request.getMethod().equalsIgnoreCase(“post”)) {
try {
// 校验验证码合法性
validate(request);
} catch (AuthenticationException e) {
// 交给失败处理器进行处理异常 也就是上文失败返回的json
customAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
// 一定要记得结束
return;
}
}
// 放行请求 往下执行过滤器
filterChain.doFilter(request, response);
}
private void validate(HttpServletRequest request) {
// 先获取seesion中的验证码
String sessionCode = (String)request.getSession().getAttribute(CODE_SESSION_KEY);
// 获取用户输入的验证码
String inpuCode = request.getParameter(“code”);
// 判断是否正确
if (StringUtils.isBlank(inpuCode)) {
throw new ValidateCodeException(“验证码不能为空”);
}
if (!inpuCode.equalsIgnoreCase(sessionCode)) {
throw new ValidateCodeException(“验证码输入错误”);
}
}
}
CodeController
获取验证按接口