Spring Security 3.2.3使用JavaConfig发布

时间:2014-05-21 16:19:02

标签: spring-security spring-java-config

我有一个用XML配置的Spring Security,运行得很好。现在,我试图只在JavaConfig中表达它,以便完全摆脱XML配置。

我查看了参考文档,以及许多博客和支持请求,但我仍然找不到解决方案。

它给了我以下例外:

Could not autowire field: private org.springframework.security.web.FilterChainProxy
com.thalasoft.learnintouch.rest.config.WebTestConfiguration.springSecurityFilterChain;

可怜我在这里发出了自己的请求......

代码:

@Configuration
@ComponentScan(basePackages = { "com.thalasoft.learnintouch.rest" })
public class WebTestConfiguration {

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private FilterChainProxy springSecurityFilterChain;

}

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}

public class WebInit implements WebApplicationInitializer {
    private static Logger logger = LoggerFactory.getLogger(WebInit.class);

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        registerListener(servletContext);

        registerDispatcherServlet(servletContext);

        registerJspServlet(servletContext);
    }

    private void registerListener(ServletContext servletContext) {
        // Create the root application context
        AnnotationConfigWebApplicationContext appContext = createContext(ApplicationConfiguration.class, WebSecurityConfiguration.class);

        // Set the application display name
        appContext.setDisplayName("LearnInTouch");

        // Create the Spring Container shared by all servlets and filters
        servletContext.addListener(new ContextLoaderListener(appContext));
    }

    private void registerDispatcherServlet(ServletContext servletContext) {
        AnnotationConfigWebApplicationContext webApplicationContext = createContext(WebConfiguration.class);

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(webApplicationContext));
        dispatcher.setLoadOnStartup(1);

        Set<String> mappingConflicts = dispatcher.addMapping("/");

        if (!mappingConflicts.isEmpty()) {
          for (String mappingConflict : mappingConflicts) {
            logger.error("Mapping conflict: " + mappingConflict);
          }
          throw new IllegalStateException(
              "The servlet cannot be mapped to '/'");
        }
    }

    private void registerJspServlet(ServletContext servletContext) {
    }

    private AnnotationConfigWebApplicationContext createContext(final Class... modules) {
        AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
        appContext.register(modules);
        return appContext;
    }

}

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomAuthenticationProvider customAuthenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticationProvider);
    }

    @Bean
    public DelegatingFilterProxy springSecurityFilterChain() {
        DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
        return filterProxy;
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").hasRole("ROLE_ADMIN").and().httpBasic();

        http.authorizeRequests().antMatchers("/admin/login", "/admin/logout", "/admin/denied").permitAll()
        .antMatchers("/admin/**").hasRole("ROLE_ADMIN")
        .and()
        .formLogin()
        .loginPage("/admin/login")
        .defaultSuccessUrl("/admin/list")
        .failureUrl("/admin/denied?failed=true")
        .and()
        .rememberMe();

        http.logout().logoutUrl("/admin/logout").logoutSuccessUrl("/admin/login").deleteCookies("JSESSIONID");
    }

}

我希望摆脱的XML配置:

<!-- A REST authentication -->
<http use-expressions="true" pattern="/admin/**">
    <intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')" />
    <http-basic entry-point-ref="restAuthenticationEntryPoint" />
    <logout />
</http>

<!-- A form based browser authentication -->
<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/admin/login" access="permitAll" />
    <intercept-url pattern="/admin/logout" access="permitAll" />
    <intercept-url pattern="/admin/denied" access="permitAll" />
    <intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
    <form-login
        login-page="/admin/login"
        default-target-url="/admin/list"
        authentication-failure-url="/admin/denied?failed=true"
        always-use-default-target="true" />
    <logout logout-success-url="/admin/login" />
    <logout delete-cookies="JSESSIONID" />
</http>

<!-- A custom authentication provider on legacy data -->
<authentication-manager>
    <authentication-provider ref="customAuthenticationProvider" />
</authentication-manager>

更新

我添加了一个配置指令:

@Configuration
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}

和一个明确的导入指令:

@Import({ SecurityWebApplicationInitializer.class })
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
}

但例外仍然完全相同。

我正在运行Spring Security 3.2.4.RELEASE和Spring 3.2.9.RELEASE

如果您有任何建议,欢迎。

1 个答案:

答案 0 :(得分:0)

我从安全配置中删除了这个bean定义,似乎已经解决了这个问题

@Bean
public DelegatingFilterProxy springSecurityFilterChain() {
    DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
    return filterProxy;
}