![](https://i-blog.csdnimg.cn/blog_migrate/3c17498746307e426e80cdf1465e8109.webp?x-image-process=image/format,png)
前述
- 源代码已经上传到,对应项目为
codefilter
,登录方式为表单登录
SpringSecurity整合验证码登录实现
一、引入依赖
<properties>
<velocity-engine-core.version>2.3</velocity-engine-core.version>
<kaptcha.version>2.3.2</kaptcha.version>
</properties>
<dependencies>
<!--验证码-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity-engine-core.version}</version>
</dependency>
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency>
</dependencies>
二、新增登录失败处理器
/**
* 登录失败处理器
*
* @author LiJunYi
* @date 2022/07/27
*/
@Component
@Slf4j
public class CustomAuthenticationFailureImpl implements AuthenticationFailureHandler
{
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
log.error(e.getMessage());
String msg = "验证码";
if (e.getMessage().contains(msg))
{
int code = HttpStatus.ERROR;
ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, e.getMessage())));
}else
{
int code = HttpStatus.UNAUTHORIZED;
msg = "用户名或密码错误";
ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
}
}
}
三、自定义验证验证码过滤器
/**
* 自定义验证代码过滤
*
* @author LiJunYi
* @date: 2022/07/27
*/
@Component
public class ValidateCodeFilter extends OncePerRequestFilter
{
@Resource
private CustomAuthenticationFailureImpl authenticationFailure;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException
{
String loginUrl = "/userLogin";
if (loginUrl.equalsIgnoreCase(request.getRequestURI())
&& HttpMethod.POST.equalsIgnoreCase(request.getMethod())) {
try {
HttpSession session = request.getSession();
// Session中的校验码
String sessionImgCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
// Session 中校验码过期时间
LocalDateTime expireTime = (LocalDateTime) session.getAttribute(Constants.KAPTCHA_SESSION_DATE);
// 客户端提交的校验码
String requestImgCode = request.getParameter(com.example.codefilter.common.constant.Constants.CAPTCHA_CODE);
if (StrUtil.isEmpty(requestImgCode)) {