WebSecurityConfigurerAdapter添加到非Servlet 3.0容器中的根上下文

时间:2013-09-13 15:52:14

标签: java spring-security annotations

我有一个示例Web应用程序,我将其用作转换现有 servlet 2.4 应用程序的示例,以便从基于XML的安全配置转移到此处所述的基于Java配置的新样式。 Spring Security Java Config Preview

我的安全配置如下:

@Configuration
@EnableWebSecurity
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

public WebSecurityConfig() {
    log.info("init");
}

@Override
protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}

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

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
    .authorizeUrls()
      .antMatchers("/","/home").permitAll() 
      .antMatchers("/secure/**").hasRole("USER")
      .anyRequest().authenticated()
      .and()
  .formLogin() 
      .loginUrl("/login") 
      .permitAll();
}
}

问题是文档/示例基于servlet 3.0规范,不使用web.xml

该文档使用AbstractAnnotationConfigDispatcherServletInitializer,但我不能在servlet 2.4容器中使用它。

我使用 web.xml 引导我的MVC应用程序:

<servlet>
    <servlet-name>my-spike</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextClass</param-name>
        <param-value>
           org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </init-param>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.example.config.WebMvcConfig</param-value>
    </init-param>
</servlet>

所以问题是如何将我的WebSecurityConfig添加到web.xml或Java代码中的根应用程序上下文中?

1 个答案:

答案 0 :(得分:0)

您应该能够通过这种方式ContextLoaderListener配置它:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value> package.WebSecurityConfig</param-value>
</context-param>
<context-param>
    <param-name>contextClass</param-name>
    <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>