无法让@EnableGlobalMethodSecurity工作

时间:2014-10-08 18:17:07

标签: java spring-security

我正在尝试在基于java的配置上配置@EnableGlobalMethodSecurity,但方面正在忽略被注释的方法。我已经介绍了相同XML配置通常遇到的所有问题,我的注释是在根上下文的安全配置部分,我的服务类也在根上下文中管理。

在下面的TestService中是一个包含我的@PreAuthorize注释的界面,我也有一个相应的实现,我也尝试过直接注释。

AppInitializer.java

public class AppInitializer
        extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{
            RootConfig.class,
            SecurityConfig.class
        };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

}

RootConfig.java

@Configuration
@ComponentScan(basePackages = {"com.acme.app.service"})
public class RootConfig {
}

SecurityConfig.java

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password("password").roles("USER").and()
            .withUser("admin").password("pass").roles("USER", "ADMIN");
    }

    @Configuration
    public static class FormLoginWebSecurityConfigurerAdapter
            extends WebSecurityConfigurerAdapter {
        @Autowired
        UserDetailsService userDetailsService;
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/static/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login").permitAll().defaultSuccessUrl("/")
                .and().logout().logoutUrl("/logout")
                .logoutSuccessUrl("/");
        }
        @Override
        protected UserDetailsService userDetailsService() {
            return userDetailsService;
        }
    }

    @Bean
    public UserDetailsService userDetailsServiceBeanCreation() {
        Collection<UserDetails> users = new ArrayList<>();
        users.add(getUser("user", "password", "USER"));
        users.add(getUser("admin", "pass", "ADMIN", "USER"));
        UserDetailsService uds = new InMemoryUserDetailsManager(users);
        return uds;
    }

    private UserDetails getUser(String user, String pass, String... roles) {
        // impl omitted...
    }

    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfigurationAdapter
            extends WebSecurityConfigurerAdapter {
        @Autowired
        UserDetailsService userDetailsService;
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/api/**")
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .httpBasic().realmName("com.acme.app")
                .and().sessionManagement();
        }
        @Override
        protected UserDetailsService userDetailsService() {
            return userDetailsService;
        }
    }
}

WebConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.acme.app.config",
                               "com.acme.app.controllers"},
               excludeFilters = {
                   @Filter(type = ASSIGNABLE_TYPE,
                           value = {
                               WebConfig.class,
                               SecurityConfig.class
                           })
               })
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("/static/");
    }

    @Bean
    public CookieLocaleResolver getLocaleResolver() {
        CookieLocaleResolver bean = new CookieLocaleResolver();
        bean.setCookieName("clientlanguage");
        bean.setCookieMaxAge(100000);
        return bean;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        registry.addInterceptor(lci);
    }

    @Bean
    public TilesConfigurer getTilesConfigurer() {
        CustomTilesInitializer ti = new CustomTilesInitializer();
        TilesConfigurer res = new TilesConfigurer();
        res.setCompleteAutoload(true);
        res.setDefinitions("/WEB-INF/**/tiles.xml");
        return res;
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.tiles();
        registry.enableContentNegotiation(new MappingJackson2JsonView());
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("home");
        registry.addRedirectViewController("/home", "/");
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/aboutme").setViewName("aboutme");
    }

}

TestService.java

public interface TestService {
    @PreAuthorize("hasAuthority('ROLE_DUMMY_ROLE')")
    BasicData getDataSecured();
}

请注意,我的pom中也有弹簧。

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
</dependency>

1 个答案:

答案 0 :(得分:4)

RootConfig扫描完成后,您的DispatcherServlet已包含在内。

我会(在这种情况下)排除自动检测到的所有@Configuration类。由于检测到您的组件扫描再次实例化bean,因此它们不属于安全方面,因为它们位于不同的上下文中。