在Spring Security中自定义一个的过滤器,将其添加到Spring Security过滤器链的合适位置。定义一个自己的过滤器类继承Filter接口即可。
但是在 Spring 体系中,推荐使用
OncePerRequestFilter来实现,它可以确保一次请求只会通过一次该过滤器(Filter实际上并不能保证这
一点)。
public class MySecurityFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
// 非登录请求,不处理
if("/login".equals(httpServletRequest.getRequestURI())&&httpServletRequest.getMethod().equals(HttpMethod.POST.name())) {
String username = httpServletRequest.getParameter("username");
String password = httpServletRequest.getParameter("password");
System.out.println("username:" + username);
System.out.println("password:" + password);
}else {
System.out.println("非登录处理!");
}
filterChain.doFilter(httpServletRequest,httpServletResponse);
}
}
创建Spring Security 配置类,继承WebSecurityConfigurerAdapter
,重写方法void configure(HttpSecurity http)
,将自定义的过滤器添加到Spring Security 过滤器链中:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
// 将自定义的过滤器添加到Spring Security 过滤器链中
http.addFilterBefore(new MySecurityFilter(),UsernamePasswordAuthenticationFilter.class);
}
}
将该过滤器添加到Spring Security的过滤器链中即可生效,Spring Security支持三种filter添加策略:
public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain, HttpSecurity> implements SecurityBuilder<DefaultSecurityFilterChain>, HttpSecurityBuilder<HttpSecurity> {
......
// 将自定义的过滤器添加在指定过滤器之后
public HttpSecurity addFilterAfter(Filter filter, Class<? extends Filter> afterFilter) {
this.comparator.registerAfter(filter.getClass(), afterFilter);
return this.addFilter(filter);
}
// 将自定义的过滤器添加在指定过滤器之前
<