Spring team recommends to use CSRF protection for any request that could be processed by a browser by normal users. If your webapp uploads any file, you should be using spring security csrf protection. Csrf protection is enabled by default so you just have to configure your webapp to handle it.
- So, at first, override beforeSpringSecurityFilterChain.
public class SecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer { @Override protected void beforeSpringSecurityFilterChain(ServletContext servletContext) { insertFilters(servletContext, new MultipartFilter()); } }
2.Then, edit or create (if you haven’t yet) a bean named “filterMultipartResolver” which is a CommonsMultipartResolver. Make sure bean has this name, because it is commonly named wrong as “multipartResolver” and doesn’t work (as described here).
@Bean(name = "filterMultipartResolver") public CommonsMultipartResolver getMultipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); return multipartResolver; }
3. Another approuch is to include the CSRF as a query parameter in the action attribute of the form (shown below), but keep in mind that the query parameter can be leaked, so a best practice is to use the first idea (step 1 and 2).
<form action="/upload?${_csrf.parameterName}=${_csrf.token}" method="post" enctype="multipart/form-data">