I\'m using Spring Web 4.0.5, Spring Security 3.2.4, Commons FileUpload 1.3.1, Tomcat 7 and I\'m getting an ugly MaxUploadSizeExceededException
when my upload si
The solution I came up with while experimenting is the following:
Extend CommonsMultipartResolver in order to swallow the exception. I add the exception to the Request just in case you want to use it in the Controller, but I don't think it's needed
package org.springframework.web.multipart.commons;
import java.util.Collections;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
public class ExtendedCommonsMultipartResolver extends CommonsMultipartResolver {
@Override
protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
try {
return super.parseRequest(request);
} catch (MaxUploadSizeExceededException e) {
request.setAttribute("MaxUploadSizeExceededException", e);
return parseFileItems(Collections.<FileItem> emptyList(), null);
}
}
}
Declare your resolver in the WebSecurityConfigurerAdapter, in place of CommonsMultipartResolver (you should declare a filterMultipartResolver in any case so nothing new here)
@Bean(name="filterMultipartResolver")
CommonsMultipartResolver filterMultipartResolver() {
CommonsMultipartResolver filterMultipartResolver = new ExtendedCommonsMultipartResolver();
filterMultipartResolver.setMaxUploadSize(MAXBYTES);
return filterMultipartResolver;
}
Remember to define the correct filter precedence in the AbstractSecurityWebApplicationInitializer as stated in the docs (you'd do this in any case)
@Order(1)
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
@Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(servletContext, new MultipartFilter());
}
}
Add the _csrf token to the form action URL (I'm using thymeleaf here)
<form th:action="@{|/submitImage?${_csrf.parameterName}=${_csrf.token}|}"
In the Controller, just check for null on the MultipartFile, something like (snippet not checked for errors):
@RequestMapping(value = "/submitImage", method = RequestMethod.POST)
public String submitImage(MyFormBean myFormBean, BindingResult bindingResult, HttpServletRequest request, Model model) {
MultipartFile multipartFile = myFormBean.getImage();
if (multipartFile==null) {
bindingResult.rejectValue("image", "validation.image.filesize");
} else if (multipartFile.isEmpty()) {
bindingResult.rejectValue("image", "validation.image.missing");
This way you can use the usual Controller method for handling the form submission even in case of size exceeded.
What I don't like of this approach is that you have to mess with an external library package (MultipartParsingResult is protected) and that you have to remember setting the token on the form url (which is also less secure btw).
What I do like is that you handle the form submission in just one place in the controller.
The problem of a big file being fully downloaded before returning to the user also persists, but I guess it is addressed somewhere else already.
The thing is springSecurityFilterChain
must be added after multipart filter. That's why you are getting 403 status. Here:
http://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html#csrf-multipartfilter
I think after you do so, you will be able to catch FileUploadBase.SizeLimitExceededException
in a @ControllerAdvice annotated class containing @ExceptionHandler
annotated methods.
I know I'm late to the party, but I found a much more elegant solution imho.
Instead of adding a filter for the multipart resolver, simply add throws MaxUploadSizeExceededException
on your controller method and add the filter for the DelegatingFilterProxy
in your web.xml
and you can add an exception handler right in your controller without having to redirect the request.
e.g.:
Method (in Controller):
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public ResponseEntity<String> uploadFile(MultipartHttpServletRequest request) throws MaxUploadSizeExceededException {
//code
}
Exception Handler (in same controller):
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ResponseEntity handleSizeExceededException(HttpServletRequest request, Exception ex) {
//code
}
Web.xml (thanks to Rob Winch):
<filter>
<description>
Secures access to web resources using the Spring Security framework.
</description>
<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>REQUEST</dispatcher>
</filter-mapping>
And that is all you need.
You can handle the MaxUploadSizeExceededException by adding an additional Filter to catch the exception and the redirect to an error page. For example, you could create a MultipartExceptionHandler Filter like the following:
public class MultipartExceptionHandler extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
filterChain.doFilter(request, response);
} catch (MaxUploadSizeExceededException e) {
handle(request, response, e);
} catch (ServletException e) {
if(e.getRootCause() instanceof MaxUploadSizeExceededException) {
handle(request, response, (MaxUploadSizeExceededException) e.getRootCause());
} else {
throw e;
}
}
}
private void handle(HttpServletRequest request,
HttpServletResponse response, MaxUploadSizeExceededException e) throws ServletException, IOException {
String redirect = UrlUtils.buildFullRequestUrl(request) + "?error";
response.sendRedirect(redirect);
}
}
NOTE: This redirect makes an assumption about your form and upload. You may need to modify where to redirect to. Specifically if you follow the pattern of your form being at GET and it is processed at POST this will work.
You can then ensure to add this Filter before MultipartFilter. For example, if you are using web.xml you would see something like this:
<filter>
<filter-name>meh</filter-name>
<filter-class>org.example.web.MultipartExceptionHandler</filter-class>
</filter>
<filter>
<description>
Allows the application to accept multipart file data.
</description>
<display-name>springMultipartFilter</display-name>
<filter-name>springMultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
<!--init-param>
<param-name>multipartResolverBeanName</param-name>
<param-value>multipartResolver</param-value>
</init-param-->
</filter>
<filter>
<description>
Secures access to web resources using the Spring Security framework.
</description>
<display-name>springSecurityFilterChain</display-name>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>meh</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springMultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>ERROR</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
In your form you can then detect if the error occurred by inspecting if the HTTP parameter error is present. For example, in a JSP you might do the following:
<c:if test="${param.error != null}">
<p>Failed to upload...too big</p>
</c:if>
PS: I created SEC-2614 to update the documentation to discuss error handling