两种实现登录验证码的思路:
目前先尝试使用自定义认证逻辑来实现登录验证码,大致流程如下:
引入验证码生成工具类,并进行配置
编写获取验证码图片接口,返回生成的验证码,并且将生成的验证码存入 HttpSession 中
提供一个新的 AuthenticationProvider,先完成验证码验证逻辑,再调用 super 完成父类验证逻辑
public class KaptchaAuthenticationProvider extends DaoAuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
String kaptcha = req.getParameter("kaptcha");
String sessionKaptcha =
(String) req.getSession().getAttribute("kaptcha");
if (kaptcha != null && sessionKaptcha != null
&& kaptcha.equalsIgnoreCase(sessionKaptcha)) {
return super.authenticate(authentication);
}
throw new AuthenticationServiceException("验证码输入错误");
}
}
最后在 SecurityConfig 中进行配置: