我有以下代码用于在 spring boot 应用程序中配置过滤器。当我发出请求时,我的第二个过滤器 B 没有被调用。
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity.ignoring().antMatchers(HttpMethod.GET, "/health");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(new A(), BasicAuthenticationFilter.class);
http.addFilterAfter(new B(), new A().getClass());
}
}
import org.springframework.web.filter.GenericFilterBean;
public class A extends GenericFilterBean {
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
System.out.println("filter A");
}
}
import org.springframework.web.filter.GenericFilterBean;
public class B extends GenericFilterBean {
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
System.out.println("filter B");
}
}
编辑:
public class A extends GenericFilterBean {
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
System.out.println("filter A Before");
arg2.doFilter(arg0,arg1);
System.out.println("filter A After");
}
}
最佳答案
您的配置是正确的。但是您需要将请求从 Filter A
传递到 Filter B
,如 M. Deinum 所述.只是打印不会工作。在您的代码中,它应该类似于 Filter A
中的 arg2.doFilter()
。
来自 docs它说,
A typical implementation of this method would follow the following pattern:
- 检查请求
- 可选择使用自定义实现包装请求对象 过滤输入过滤的内容或标题
- 可选择使用自定义实现包装响应对象以 过滤内容或标题以进行输出过滤
- 使用 FilterChain 调用链中的下一个实体 object (chain.doFilter()),或者不传递请求/响应对 到过滤器链中的下一个实体以阻止请求 处理
- 在调用 next 后直接在响应上设置 header 过滤器链中的实体。
关于java - 未调用 Spring Security 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33519119/