Uploading File Returns 403 Error - Spring MVC

前端 未结 4 1461
鱼传尺愫
鱼传尺愫 2021-01-05 02:25

In my Spring MVC project I am trying to upload a file via a simple form.

HTML Form:

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-05 02:43

    This is covered in the CSRF - Multipart (File Upload) section of the Spring Security reference. You have two options:

    • Placing MultipartFilter before Spring Security
    • Include CSRF token in action

    Placing MultipartFilter before Spring Security

    The first option is to ensure that the MultipartFilter is specified before the Spring Security filter. 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 negligble 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:

    
        MultipartFilter
        org.springframework.web.multipart.support.MultipartFilter
    
    
        springSecurityFilterChain
        org.springframework.web.filter.DelegatingFilterProxy
    
    
        MultipartFilter
        /*
    
    
        springSecurityFilterChain
        /*
    
    

    Include CSRF token in action

    If allowing unauthorized users to upload temporariy 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

    
    

    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. Additional information can be found in RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI’s.

提交回复
热议问题