public class ValidateCodeUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private String defaultFilterProcessesPath;
public ValidateCodeUsernamePasswordAuthenticationFilter(String defaultFilterProcessesUrl, String failureUrl) {
super(defaultFilterProcessesUrl);
this.defaultFilterProcessesPath = defaultFilterProcessesUrl;
setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(failureUrl));
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessesPath.equalsIgnoreCase(request.getServletPath())) {
String validateCode = request.getParameter("verifitcaionCode");
String realVailDateCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_CONFIG_KEY);
// equalsIgnoreCase比较时忽略大小写
if (realVailDateCode != null && !realVailDateCode.equalsIgnoreCase(validateCode)) {
unsuccessfulAuthentication(request, response, new InsufficientAuthenticationException("输入的验证码不正确"));
return;
}
}
chain.doFilter(req, res);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
return null;
}
}
在DispatcherServlet中注册KaptchaServlet servlet
public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encoding-filter", CharacterEncodingFilter.class);
encodingFilter.setInitParameter("encoding", "UTF-8");
encodingFilter.setInitParameter("forceEncoding", "true");
encodingFilter.setAsyncSupported(true);
encodingFilter.addMappingForUrlPatterns(null, true, "/*");
ServletRegistration.Dynamic kaptchaServlet = servletContext.addServlet("kaptcha-servlet", KaptchaServlet.class);
kaptchaServlet.addMapping("/kaptcha/getKaptchaImage");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.addFilterBefore(new ValidateCodeUsernamePasswordAuthenticationFilter("/login", "/login?error"), UsernamePasswordAuthenticationFilter.class)}
로그인 페이지를 찾을 수 없나요? 누군가 이런 문제를 겪은 적이 있는 것 같은데 저는 4번을 사용해 본 적이 없습니다. 아마도 인증코드와는 관련이 없을 것 같습니다. 먼저 주석을 달고 살펴보세요