Spring Security 3.2 CSRF support for multipart requests

后端 未结 4 1212
暗喜
暗喜 2020-11-27 15:43

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 w

4条回答
  •  渐次进展
    2020-11-27 16:20

    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 tags in the header would also work just fine by halting the request on submit, adding the header via javascript, and then finish submitting:

    
    
        
        
        
        
    
    
        
        
    
    
    

    More info: Spring Security - CSRF for AJAX and JSON Requests

提交回复
热议问题