使用 Java Config 在多个 HttpSecurity 对象中自定义身份验证过滤器

oli*_*ver 5 java spring spring-mvc spring-security

我想使用 spring boot 和 spring java config 有两个不同的 http web 配置和自定义身份验证过滤器。我遵循了可以在这里找到的示例应用程序:https : //github.com/spring-projects/spring-security-javaconfig/blob/master/samples-web.md#sample-multi-http-web-configuration。我的理解是,对于每个 Web 配置,这最终会出现在单独的弹簧过滤器链中。但是尽管 web 配置 url 模式与请求不匹配,但两个过滤器都会被调用。例如,请求http://localhost:8080/api/dosomething将调用两个过滤器,而不仅仅是 CustomApiAuthenticationFilter。当然,可以检查 doFilterInternal 中的请求 url,如果不匹配则忽略该请求,但我认为这应该通过尊重相应 Web 配置的 url 模式自动完成。此外,我的 RestController 不会分别被调用 Postman 只收到状态代码 200 OK 没有响应正文。

两个问题: 1. 这种行为是设计使然还是配置错误?2. 为什么我的 RestController 没有被调用?

@EnableWebSecurity
public class SecurityConfiguration {

    @Configuration
    @Order(1)
    public static class ApiConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Bean
        public GenericFilterBean apiAuthenticationFilter() {
            return new CustomApiAuthenticationFilter();
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {

            http.antMatcher("/api/**").addFilterAfter(apiAuthenticationFilter(), AbstractPreAuthenticatedProcessingFilter.class)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests().antMatchers("/api/**").authenticated();
        }
    }

    @Configuration
    @Order(2)
    public static class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Bean
        public GenericFilterBean webAuthenticationFilter() {
            return new CustomWebAuthenticationFilter();
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/").addFilterAfter(webAuthenticationFilter(), AbstractPreAuthenticatedProcessingFilter.class)
                .authorizeRequests().antMatchers("/").authenticated();
        }
    }
}

public class CustomApiAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        Authentication auth = new UsernamePasswordAuthenticationToken("sub", "password", ImmutableList.of(new SimpleGrantedAuthority("API")));
        SecurityContextHolder.getContext().setAuthentication(auth);
    }
}

public class CustomWebAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        Authentication auth = new UsernamePasswordAuthenticationToken("sub", "password", ImmutableList.of(new SimpleGrantedAuthority("USER")));
        SecurityContextHolder.getContext().setAuthentication(auth);
    }
}

@RestController
public class ApiController {
    @RequestMapping(value = "/api/v1/dosomething", method = RequestMethod.GET)
    public String getSomething() {
        return "something";
    }
}
Run Code Online (Sandbox Code Playgroud)

oli*_*ver 0

除了我之前的回答之外,还可以@Bean通过手动创建相应的springFilterRegistrationBean并禁用自动过滤器注册来保留注释。这也将保留过滤器中的自动装配。

public class SecurityConfiguration {

    @Configuration
    @Order(1)
    public static class ApiConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Bean
        public FilterRegistrationBean customApiAuthenticationFilterRegistration() {
            FilterRegistrationBean registration = new FilterRegistrationBean(customApiAuthenticationFilter());
            registration.setEnabled(false);
            return registration;
        }

        @Bean
        public GenericFilterBean customApiAuthenticationFilter() {
            return new CustomApiAuthenticationFilter();
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/api/**").addFilterAfter(customApiAuthenticationFilter(), AbstractPreAuthenticatedProcessingFilter.class)
                .authorizeRequests().anyRequest().hasRole("API").and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        }
    }

    @Configuration
    @Order(2)
    public static class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Bean
        public FilterRegistrationBean customWebAuthenticationFilterRegistration() {
            FilterRegistrationBean registration = new FilterRegistrationBean(customWebAuthenticationFilter());
            registration.setEnabled(false);
            return registration;
        }

        @Bean
        public GenericFilterBean customWebAuthenticationFilter() {
            return new CustomWebAuthenticationFilter();
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/").addFilterAfter(customWebAuthenticationFilter(), AbstractPreAuthenticatedProcessingFilter.class)
                .authorizeRequests().antMatchers("/").hasRole("USER");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)