多个WebSecurityConfigurerAdapter冲突问题

时间:2016-02-01 15:17:37

标签: spring-security filter

我正在构建一个需要处理两种身份验证的应用程序,所以我这样做了

@Autowired
UserService userService;

@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    // Md5PasswordEncoder encoder = new Md5PasswordEncoder();
    auth.userDetailsService(userDetailsService());// .passwordEncoder(encoder);
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/api/**");
}

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

    http.authorizeRequests().antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')").and().formLogin()
            .loginPage("/login").usernameParameter("username").passwordParameter("password").and()
            .exceptionHandling().accessDeniedPage("/access_denied").and().csrf().disable();
}

@Override
protected UserDetailsService userDetailsService() {
    return (UserDetailsService) userService;
}

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
@Order(Ordered.LOWEST_PRECEDENCE)
public static class ApiSecurityConfiguration extends WebSecurityConfigurerAdapter {

    AuthenticationTokenFilter authenticationTokenFilter;

    @Autowired
    CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

    @Autowired
    TokenUtils tokenUtils;

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

        authenticationTokenFilter = new AuthenticationTokenFilter(authenticationManager(), tokenUtils);

        http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()//.antMatchers("/api/authenticate", "/admin/**").permitAll()
                .antMatchers("/api/**").authenticated().and()
                .addFilterBefore(authenticationTokenFilter, AnonymousAuthenticationFilter.class).httpBasic()
                .authenticationEntryPoint(customAuthenticationEntryPoint);
    }
}

如果我使用@Order(Ordered.HIGHEST_PRECEDENCE),ApiSecurityConfiguration工作正常,第一个配置错过了, 如果我把它切换到@Order(Ordered.LOWEST_PRECEDENCE),第一个工作完美,ApiSecurityConfiguration错过了,甚至添加的过滤器不再被激活,我认为他们互相冲突,一个禁用另一个,任何建议?

1 个答案:

答案 0 :(得分:0)

您必须更改两个配置的antMatcher,我的意思是,在两个配置中,antMatcher url必须唯一。如果您编写了不同的antMatcher网址,则应该解决您的问题