验证码网上有,可以参考下
先实现获取验证码
@GetMapping(value = "/verify-code")
public String verityCode(HttpServletResponse response, HttpSession session)
{
Captcha captcha = new Captcha();
BufferedImage image = captcha.getImageCode(68, 35);
String code = captcha.getCode();
session.setAttribute("verifyCode", code);
try {
OutputStream out = response.getOutputStream();
ImageIO.write(image, "JPEG", out);
} catch (Exception e) {
return "redirect:/backend/login?error=fail";
}
return null;
}
第二步: 验证码过滤,自定义过滤
public class VerifyCaptchaFilter extends OncePerRequestFilter {
private AuthenticationFailureHandler authenticationFailureHandler;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (request.getRequestURI().equals("/auth/login-in") && request.getMethod().equalsIgnoreCase("post")) {
try {
VerifyCode(request);
} catch (VerifyCaptchaException e) {
authenticationFailureHandler.onAuthenticationFailure(request, response, e);
return;
}
}
filterChain.doFilter(request, response);
}
private void VerifyCode(HttpServletRequest request) throws ServletRequestBindingException {
String code = request.getParameter("code");
String sessionCode = request.getSession().getAttribute("verifyCode").toString();
if (!code.equalsIgnoreCase(sessionCode)) {
throw new VerifyCaptchaException("verify_error");
}
request.getSession().removeAttribute("verifyCode");
}
public AuthenticationFailureHandler getAuthenticationFailureHandler() {
return authenticationFailureHandler;
}
public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
this.authenticationFailureHandler = authenticationFailureHandler;
}
}
3. 自定义异常处理
public class VerifyCaptchaException extends BadCredentialsException {
public VerifyCaptchaException(String msg) {
super(msg);
}
}
4:自定义登录错误处理
public class LoginFailHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
httpServletResponse.sendRedirect("/auth/login?error=" + e.getMessage());
}
}
5:在secruity配置中使用
VerifyCaptchaFilter verifyCaptchaFilter = new VerifyCaptchaFilter();
LoginFailHandler loginFailHandler = new LoginFailHandler();
verifyCaptchaFilter.setAuthenticationFailureHandler(loginFailHandler);
http.addFilterBefore(verifyCaptchaFilter, UsernamePasswordAuthenticationFilter.class)
.formLogin()....
6: 在登录页面使用
<div class="login-error" th:if="${param.error}">
<span th:if="${#strings.trim(param.error) eq 'verify_error'}" th:text="验证码错误"></span>
<span th:unless="${#strings.trim(param.error) eq 'verify_error'}" th:text="用户名或密码错误"></span>
</div>