Tag: Spring

How to handle Multpart file upload with Spring Security CSRF Protection (no xml)

How to handle Multpart file upload with Spring Security CSRF Protection (no xml)

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.

  1. 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">

GitHub: Complete working example

Routes API

Routes API

This a Rest API to create optimized travelling routes using Google Maps API. Spring Framework is responsible for MVC structure and data is handled by a NoSQL Database, MongoDB.

Example Json Entry:

example json

It returns a Json with a list of lat and lng, witch means the best route way through those initial points.

GitHub: Routes API

Used Technologies:  Java, SpringBoot, MongoDB, Maven