Spring Security 3.2 CSRF support for multipart requests - spring

We have been using Spring Security with our application for a few years now. Last week we upgraded Spring Security from version 3.1.4 to 3.2.0. The upgrade went fine and we did not find any errors post the upgrade.
While looking through the Spring Security 3.2.0 documentation we came across the newly added features around CSRF protection and security headers. We followed the instructions in the Spring Security 3.2.0 documentation to enable CSRF protection for our protected resources. It works fine for regular forms but does not work for multipart forms in our application. On form submission, CsrfFilter throws an Access Denied error citing the absence of a CSRF token in the request (determined through DEBUG logs). We have tried using the first option suggested in the Spring Security documentation for making CSRF protection work with multipart forms. We do not want to use the second suggested option as it leaks CSRF tokens through the URLs and poses a security risk.
The relevant part of our configuration based on the documentation is available as a Gist on Github. We are using Spring version 4.0.0.
Note that we have already tried the following variations without success:
Not declaring the MultipartFilter in web.xml.
Not setting the resolver bean name for the MultipartFilter in web.xml.
Using the default resolver bean name filterMultipartResolver in webContext.xml.
UPDATE: I have confirmed that the documented behaviour does not work even with a single page sample app. Can anyone confirm that the documented behaviour works as expected? Is there an example working application that can be used?

I was able to resolve this with help from the Spring Security team. I have updated the Gist to reflect a working configuration. I had to follow the steps given below in order to get everything to work as expected.
1. Common Step
Add a MultipartFilter to web.xml as described in the answer by #holmis83, ensuring that it is added before the Spring Security configuration:
<filter>
<display-name>springMultipartFilter</display-name>
<filter-name>springMultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>springMultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<display-name>springSecurityFilterChain</display-name>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>ERROR</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
2.1. Using Apache Commons Multipart Resolver
Ensure that there is an Apache Commons Multipart Resolver bean named filterMultipartResolver in the root Spring application context. I will stress this again, make sure that the Multipart Resolver is declared in the root Spring Context (usually called applicationContext.xml). For example,
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:springWebMultipartContext.xml
</param-value>
</context-param>
springWebMultipartContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="filterMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000000" />
</bean>
</beans>
Make sure that the bean is called filterMultipartResolver as any other bean name is not picked up by MultipartFilter configured in web.xml. My initial configuration was not working because this bean was named multipartResolver. I even tried passing the bean name to MultipartFilter using web.xml init-param but that did not work either.
2.2. Using Tomcat Multipart support
Tomcat 7.0+ has in-built multipart support, but it has to be explicitly enabled. Either change the global Tomcat context.xml file as follows or include a local context.xml file in your WAR file for this support to work without making any other changes to your application.
<Context allowCasualMultipartParsing="true">
...
</Context>
After these changes using Apache Commons Multipart Resolver our application is working so far on Tomcat, Jetty and Weblogic.

This part:
<filter-mapping>
<filter-name>multipartFilter</filter-name>
<servlet-name>/*</servlet-name>
</filter-mapping>
Should be:
<filter-mapping>
<filter-name>multipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
It is an error in Spring Security 3.2.0 documentation. The bug has been reported and will be fixed in upcoming version.

After struggling with this issue a bit, I found a much easier solution by just using the Request Header defined in Spring Security instead of trying to get the CSRF token embedded as a part of the multipart content.
Here is a simple way I setup the header using an AJAX library for file upload in my jsp:
var uploader = new AjaxUpload({
url: '/file/upload',
name: 'uploadfile',
multipart: true,
customHeaders: { '${_csrf.headerName}': '${_csrf.token}' },
...
onComplete: function(filename, response) {
...
},
onError: function( filename, type, status, response ) {
...
}
});
Which in turn sent the multipart request with header:
X-CSRF-TOKEN: abcdef01-2345-6789-abcd-ef0123456789
Their recommendations for embedding into <meta /> tags in the header would also work just fine by halting the request on submit, adding the header via javascript, and then finish submitting:
<html>
<head>
<meta name="_csrf" content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<!-- ... -->
</head>
<body>
<!-- ... -->
<script>
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
// Do whatever with values
</script>
</body>
</html>
More info: Spring Security - CSRF for AJAX and JSON Requests

Find most answer is answered server years ago.
If you need
Passing CSRF tokens with RestTemplate
This blog is quite enlightening https://cloudnative.tips/passing-csrf-tokens-with-resttemplate-736b336a6cf6
In Spring Security 5.0.7.RELEASE
https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-multipart
There are two options to using CSRF protection with
multipart/form-data. Each option has its tradeoffs.
-Placing MultipartFilter before Spring Security
-Include CSRF token in
action
For short, the first option is safer, the latter is easier.
Specifying the MultipartFilter before the Spring Security filter
means that there is no authorization for invoking the MultipartFilter
which means anyone can place temporary files on your server. However,
only authorized users will be able to submit a File that is processed
by your application. In general, this is the recommended approach
because the temporary file upload should have a negligible impact on
most servers.
To ensure MultipartFilter is specified before the Spring Security
filter with java configuration, users can override
beforeSpringSecurityFilterChain as shown below:
public class SecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
#Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(servletContext, new MultipartFilter());
}
}
To ensure MultipartFilter is specified before the Spring Security
filter with XML configuration, users can ensure the
element of the MultipartFilter is placed before the
springSecurityFilterChain within the web.xml as shown below:
<filter>
<filter-name>MultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>MultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Another option
If allowing unauthorized users to upload temporary files is not
acceptable, an alternative is to place the MultipartFilter after the
Spring Security filter and include the CSRF as a query parameter in
the action attribute of the form. An example with a jsp is shown below
<form action="./upload?${_csrf.parameterName}=${_csrf.token}" method="post" enctype="multipart/form-data">
The disadvantage to this approach is that query parameters can be
leaked. More genearlly, it is considered best practice to place
sensitive data within the body or headers to ensure it is not leaked.

Related

Spring Session and Spring Security (3.2.X RELEASE)

We have a web application built upon Spring Framework 3.2.x (3.2.12-RELEASE at moment) and Spring Security 3.2.x (i.e 3.2.5-RELEASE)
Security is implemented with classical Spring approach. In web.xml we load ApplicationContext and springSecurityFilterChain
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:META-INF/spring/applicationContext*.xml
</param-value>
</context-param>
...
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
As of a change in requirements, we are trying to investigate on how to permit different HttpSessions per tab (or window) within the same browser: in this scenario the same physical user can log in the application using two separate app-users.
I can understand that this is not possibile using JSESSIONID cookie approach. I'm trying using Spring Session (Spring Session and Spring Security
and Spring Session Multiple Session) but i can't manage doing it, having difficulties mixing my XML configuration with the JavaConfig approach shown in links before, Tomcat does not even start with a lot of errors.
I'm new with mixing XML and JavaConfig approch, so..can anyone give me an hint in how to proceed with Spring Session?
Are there other ways to fulfill my requirement?
Spring Session project actually contains a few sample projects that demonstrate usage with Spring XML config. Look for the samples with -xml suffix in the sample name.
Generally speaking, what you need to do is manually register appropriate #Configuration class as a #Bean. For example, if you want to use Spring Session backed by Redis, register RedisHttpSessionConfiguration. You'll find the correct #Configuration class to use by looking at appropriate #Enable*HttpSession annotation (in this case #EnableRedisHttpSession) and determining which class is imported via #Import annotation.

Spring CSRF not working on Tomcat 7.0.28

I have a web application which uses Spring Security, version 4.0.1 and Spring version 4.1.6.
In every page of the web app I have the
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
parameter which sends the CSRF token to the server. Now my problem is that if I see the source code of the jsp I have
<input type="hidden" name="" value=""/>
so the token is not sent to the server and the post action results in the message HTTP Status 405 - Request method 'POST' not supported
If I deploy the same web application on Tomcat 7.0.5.x everything works fine, and it also works fine in WAS 7, WAS 8.5 and Jboss EAP 6.4.
I can not understand why on this version of Tomcat (7.0.28), which I downloaded from the web site without changing anything about configuration etc. , the CSRF protection offered by Spring Security is not working.
I faced the same problem: Tomcat 7.0.28 is not able to auto detect spring security filter.
My solution is to add this :
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
to the web.xml and try again.
Open tomacat/confg folder
see there is a file Context.xml and open it
change <Context> to <Context useHttpOnly="false">
then you have done.

Spring Security with PrimeFaces Dialog Framework

I have a web Project which uses Spring security and Primefaces.
I am trying to use Primefaces Dialog Framework to call any XHTML File as a dialog .. my problem is when I add this line on my web.xml:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The dialog Box doesn't appear , if I remove the line above , the dialog box is being displayed .. but If I remove the lines above , I loose the spring security feature .. any configuration I missed?
Yes, Spring Security is blocking the frame generated by Primefaces. You can make it work by adding the following directive to Spring Security configuration
http
// ...
.headers().frameOptions().sameOrigin();
source:
http://docs.spring.io/spring-security/site/docs/current/reference/html/headers.html#headers-frame-options

How to temporarily disable Spring Security in Spring Web App

First, I am a complete noob when it comes to Spring. An application was left to me to work on by a colleague who is now on vacation. He told me to leave security alone, as the final approach is not decided yet, and just develop the rest of the application.
However security is enabled and prevents access to the main web page. I've checked several documents including
Disable Spring Security from spring-security.xml file
Disable Basic Authentication while using Spring Security Java configuration
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-security.html
http://docs.spring.io/spring-boot/docs/current/reference/html/howto-security.html
without finding an answer that works.
I did the following:
Added index.html to <welcome-file-list> in web.xml. This directs me to the login page which was already included in the package I took over. So, I figured I could simply disable security.
In the spring security.xml added the attribute security="none". Now I no longer get the login page. I get a blank page.
In web.xml disabled
<!-- <filter> -->
<!-- <filter-name>springSecurityFilterChain</filter-name> -->
<!-- <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> -->
<!-- </filter> -->
<!-- <filter-mapping> -->
<!-- <filter-name>springSecurityFilterChain</filter-name> -->
<!-- <url-pattern>/*</url-pattern> -->
<!-- </filter-mapping> -->
Still get blank page.
I see lots of other advice, but it assumes a lot more Spring knowledge than I currently have.
For example in the 4th link above I see:
If you define a #Configuration with #EnableWebSecurity anywhere in
your application it will switch off the default webapp security
settings in Spring Boot.
I don't know what they mean. I assume this means to put these annotations on some method somewhere, but I can't believe that this can go ANYWHERE in any java class in the application. Is there an example of doing this?
Can someone point me in the correct direction? Thanks.
Comment out <intercept-url pattern="" access="" /> tags in security XML file and give access to all the pages. This should work.
This seemed to work (in spring-security.xml)
<!-- <intercept-url pattern="/**" access="hasRole('ROLE_USER')" /> -->
<intercept-url pattern="/**" access="permitAll" />
check your web.xml or your appContext.xml to find where is loaded the spring security.xml beans(it will be like <import resource=../spring security.xml>) and comment this out , also check the beans that are loaded from there before disabling it , cause it might redirecting or whatever

GWT web.xml - java ee - login and session

I'd like to know if there is a way to provide login support fora all web application content. I mean when user tries to access some site (also static content - html), and he isn't logged or session expires he should be redirected to login site.
Html filter in web.xml for logging is almost what I need, but I also need authentication of html pages.
<filter>
<filter-name>AuthenticationFilter</filter-name>
<filter-class>example.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
This doesn't work with html pages, only servlet requests.
This should be generic mechanism, not like i.e. writing in every servlet session checking.
Thanks for all resopnes.
There are standard web.xml configuration options for defining this.
You shouldn't have to define a custom filter.
See http://download.oracle.com/docs/cd/B31017_01/web.1013/b28967/adding_security003.htm
If your application contains pages that require a user to be authenticated against a data store in order to be accessed, you must declare the following in the web.xml configuration file:
<security-role> defines valid roles in the security context.
<login-config> defines the protocol for authentication, for example form-based or HTTPS.
<security-constraint> defines the resources specified by URL patterns and HTTP methods that can be accessed only by authorized users or roles.
<servlet> defines the servlet that provides authentication.
<servlet-mapping> maps the servlet to a URL pattern.
defines the filter used to transform the content of the authentication request.
<filter-mapping> maps the filter to the file extensions used by the application. For details about the ADF binding filter, see Configuring the ADF Binding Filter.

Resources