Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 851
Alavalathi Avatar asked Aug 11 '26 15:08

Alavalathi


2 Answers

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.

like image 118
dur Avatar answered Aug 14 '26 08:08

dur


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>
like image 40
ike3 Avatar answered Aug 14 '26 08:08

ike3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!