Spring Security自定义过滤器

在使用Spring Security时,添加了验证码功能。但要对验证码进行验证,需要在过滤器中认证。

一、自定义过滤器类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.yuanli.campustradingplatform.config;

import com.yuanli.campustradingplatform.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
* @author YuanLi
* @version 1.0
* @date 2022/3/26 10:20
*/
@Component
public class VerificationCodeFilter extends GenericFilterBean {
private String filterUrl="/mylogin";

private String filterMethod="POST";

@Autowired
RedisUtil redisUtil;

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
String method = request.getMethod();
String servletPath = request.getServletPath();
if( filterMethod.equals(method) && filterUrl.equals(servletPath) ){
//验证码验证逻辑
String captcha = request.getParameter("captcha");
if( captcha.equals("") || captcha==null){
throw new AuthenticationServiceException("验证码不能为空!");
}
String captchaKey = request.getParameter("captchaKey");
String redisCaptcha = (String) redisUtil.get(captchaKey);
boolean result = captcha.equalsIgnoreCase(redisCaptcha);
if(!result){
throw new AuthenticationServiceException("验证码错误!");
}

}
filterChain.doFilter(servletRequest,servletResponse);
}
}

二、在SecurityConfig中添加配置

1
http.addFilterBefore(verificationCodeFilter, UsernamePasswordAuthenticationFilter.class);

参考:https://www.baeldung.com/spring-security-custom-filter

https://www.javadevjournal.com/spring-security/custom-filter-in-spring-security/

http://www.javaboy.org/2020/0303/springsecurity-verifycode.html