spring security下fileupload上传文件被拦截 | 您所在的位置:网站首页 › 上传文件被防火墙拦截 › spring security下fileupload上传文件被拦截 |
fileupload插件github网址 fileupload插件jQuery网站 spring mvc+fileupload例子 好了,从刚开始引入js文件的时候就入了坑: 我引入的时候按照以上顺序!!后来发现直接找不到方法: $('#file').fileupload();才发现要按照以下顺序: 把jquery.fileupload.js放在最后面,这样才能在里面引用到其他js文件。 那么在Security里要post数据,必须要有csrf的token,否则一定会有403拒绝访问的壁要碰的 …… 有三种方法: 1. 直接将multipartfilter置于springSecurityFilterChain之上,这样就上传文件的时候就会先被multipartfilter拦截,而不会受到security的保护: 重写此方法: public class SecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer { @Override protected void beforeSpringSecurityFilterChain(ServletContext servletContext) { insertFilters(servletContext, new MultipartFilter()); } }在xml配置中确保MultipartFilter 被放在springSecurityFilterChain之前: MultipartFilter org.springframework.web.multipart.support.MultipartFilter springSecurityFilterChain org.springframework.web.filter.DelegatingFilterProxy MultipartFilter /* springSecurityFilterChain /*这样,简单粗暴的解决了(当时这样,谁都可将文件上传到服务器,被短暂的保存起来,只有被授权的用户才可以上传一个被应用处理的文件。在大多数情况下,这些暂时被保存的文件不会有太大的问题,因为框架会定期自动清理。) 2.将csrf的token作为url参数: 但是这样就导致token泄露了。 如果放到hidden区域里: 可能因为commons-fileupload组件对request进行封装的时候对csrf的支持有问题,没有传递csrf值。所以被over掉了……. 用AjaxUpload上传: 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 ) { ... } });但是网上没有找到此插件…….pass掉 4.用fileupload插件: $('#file').fileupload({ dataType: 'json', add: function (e, data) { data.context = $('').text('Upload') .appendTo(document.body) .click(function () { data.context = $('').text('Uploading...').replaceAll($(this)); data.submit(); }); }, done: function (e, data) { data.context.text('Upload finished.'); } });但是在jquery.fileupload.js里找了好久,发现了一个方法:_initXHRData: function (options) 跟设置request headers有点关系。可是怎么讲csrf的header和token传进去呢?!后来想到我可以直接用ajaxSend先设置requestHeader不就行了!!! 解决Spring Security 表单上传文件CSRF失效的问题 $(document).ready(function() { var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name='_csrf_header']").attr("content"); $(document).ajaxSend(function(e, xhr, options) { xhr.setRequestHeader(header, token); }); $('#file').fileupload({ dataType: 'json', add: function (e, data) { data.context = $('').text('Upload') .appendTo(document.body) .click(function () { data.context = $('').text('Uploading...').replaceAll($(this)); data.submit(); }); }, done: function (e, data) { data.context.text('Upload finished.'); } });就酱紫,折腾了半天文档,还是用这种方法解决了!!! PS:如果用的是thymeleaf模板,注意用的是:th:content 参考:stackoverflow上类似解决方法 stackoverflow另一个网址 另外付一个用JSP的Taglib解决方法 Name: ... 还有一个:方法。 |
CopyRight 2018-2019 实验室设备网 版权所有 |