Search code examples
javaspringservletsspring-securitytomcat6

Spring Security Java configuration without Spring/Spring MVC


There are a few similar looking questions in stackoverflow, but none of them seems to answer it clearly.

I'm adding Spring Security to an existing web application which doesn't use Spring or Spring MVC. I only need the Spring Security filter, and nothing else (no MVC etc). My XML based configuration works perfectly fine, but not the Java configuration. I was mostly following this guide. For some reason the Spring Security filter doesn't seem to be available.

So the security configuration is as below - SecurityConfig.java

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

And the SecurityWebApplicationInitializer.java

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
    public SecurityWebApplicationInitializer() {
        super(SecurityConfig.class);
    }
}

What am I doing wrong above? How does the SecurityWebApplicationInitializer gets initialized and load the security config? Is the initialization part of the servlet context loading - which I have to explicitly define somewhere?


Solution

  • Tomcat 6 doesn't support Servlet API 3+, see Wikipedia:

    First Apache Tomcat release to support the Servlet 2.5, JSP 2.1, and EL 2.1 specifications.

    You need a container with Servlet API 3+, see Spring Security Reference:

    The next step is to register the springSecurityFilterChain with the war. This can be done in Java Configuration with Spring’s WebApplicationInitializer support in a Servlet 3.0+ environment.

    You could use Tomcat 7 (or higher), see Wikipedia:

    First Apache Tomcat release to support the Servlet 3.0, JSP 2.2, and EL 2.2 specifications.