spring security针对不同路径

时间:2017-06-16 03:25:16

标签: spring-security

filterOne仅适用于路径/1,而filterTwo仅适用于/2

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .antMatcher("/1")
                .addFilterAfter(filterOneBean(), BasicAuthenticationFilter.class)
                .authorizeRequests()
                .and()
                .antMatcher("/2")
                .addFilterAfter(filterTwoBean(), BasicAuthenticationFilter.class)
                .authorizeRequests()
                .and();

/1不会调用filterOnefilterTwo,而/2仅调用filterOne。为什么以及如何解决它?

编辑:以下配置仍会为filterOne

输入/2
    @SuppressWarnings("SpringJavaAutowiringInspection")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MultiHttpSecurityConfig {

    @Bean
    public FilterTwo setFilterTwo() {
        return new FilterTwo();
    }

    @Bean
    public FilterOne setFilterOne() {
        return new FilterOne();
    }


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    }

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

        @Autowired
        private FilterTwo filterTwo;

        protected void configure(HttpSecurity http) throws Exception {
            http.addFilterAfter(filterTwo, BasicAuthenticationFilter.class)
                .antMatcher("/2")
                .authorizeRequests()
                .anyRequest()
                .authenticated();
        }
    }

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

        @Autowired
        private FilterOne filterOne;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.addFilterAfter(filterOne, BasicAuthenticationFilter.class)
                .antMatcher("/1")
                .authorizeRequests()
                .anyRequest()
                .authenticated();
        }
    }
}

我可能会重申我想要实现的目标:/1/2具有不同的身份验证规则,并且它们在自定义身份验证过滤器中实现,因此它们各自具有不同的过滤器链。

编辑2:我发现filterTwo和一个filterChain对象ID不同,这是因为setAuthentication方法。

public class FilterTwo extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain)
        throws ServletException, IOException {
        ...
        SecurityContextHolder.getContext().setAuthentication(authentication); // This causes filterTwo invoked. 

        chain.doFilter(request,response);
    }
}

0 个答案:

没有答案