Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security without web.xml

Tags:

What is the recommended way to add Spring Security to a web application that is using Spring's new WebApplicationInitializer interface instead of the web.xml file? I'm looking for the equivalent of:

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

UPDATE
The provided answers are reasonable but they both assume that I've got a servletContext instance. I've looked through the hierarchy of WebApplicationInitializers and I don't see any access to the servlet context unless I choose to override one of Spring's initializer methods. AbstractDispatcherServletInitializer.registerServletFilter seems like the sensible choice but it doesn't default to URL pattern mapping and I'd hate to change filter registration for everything if there is a better way.

like image 331
Jeff Avatar asked Jan 07 '13 22:01

Jeff


People also ask

Do We Need web xml in Spring boot?

xml file is required! When required, however, we can take control over parts of the configuration and override the conventions that Spring Boot puts in play. We can also, if we really must, use traditional XML configuration files for some parts of the configuration.

Is web xml necessary?

Since the servlet 3 specification (IIRC) a web. xml is not needed anymore.

Why do we need web xml in Spring?

In Spring MVC, web. xml used to be the place, where you needed to declare and configure Dispatcher Servlet, which is a Front Controller, receiving all the requests and dispatching to all the other components such as Controllers. Fortunately, Spring offers a convenient, XML-free way of declaring Dispatcher Servlet.

Does Spring boot avoid xml configuration?

Advantages of Spring Boot:It avoids writing lots of boilerplate Code, Annotations and XML Configuration. It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc.


1 Answers

This is the way that I have done it:

container.addFilter("springSecurityFilterChain", new DelegatingFilterProxy("springSecurityFilterChain"))
                    .addMappingForUrlPatterns(null, false, "/*");

container is an instance of ServletContext

like image 184
Biju Kunjummen Avatar answered Sep 24 '22 13:09

Biju Kunjummen