Alavalathi
Alavalathi

Reputation: 753

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?

Upvotes: 3

Views: 3801

Answers (2)

dur
dur

Reputation: 17009

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.

Upvotes: 3

ike3
ike3

Reputation: 1800

How does the SecurityWebApplicationInitializer gets initialized and load the security config ?

From the guide:

  • Add a ContextLoaderListener that loads the WebSecurityConfig.

This listener is responsible for initializing the configuration. It should be someting like:

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

The listener will load applicationContext.xml which should contain a component-scan where to find your beans, e.g.:

<beans ...>
     <context:component-scan base-package="your.package.here"/>
</beans>

Upvotes: 1

Related Questions