尝试上传时无效的CSRF令牌Spring 4 MVC

我试图使用Spring MVC 4上传一个带有Web应用程序的文件,但是我收到一个错误:

在请求参数’_csrf’或标题’X-CSRF-TOKEN’上找到无效的CSRF令牌’null’。

春季版:

Spring Version 4.1.7.RELEASE

Spring Security 4.0.1.RELEASE

码:

web.xml中

  FATCA Web Application  contextConfigLocation  /WEB-INF/spring-web-servlet.xml    spring-web org.springframework.web.servlet.DispatcherServlet 1   spring-web *.html   

弹簧网络servlet.xml中

             /WEB-INF/views/   .jsp    

Settings.jsp

 
<input type="submit" value= />

在提交包含字符串“Test”的名为test.txt的文件后发布请求有效内容:

 Content-Type: multipart/form-data; boundary=---------------------------83935555814334632461054528816 Content-Length: 368 -----------------------------83935555814334632461054528816 Content-Disposition: form-data; name="file"; filename="test.txt" Content-Type: text/plain Test -----------------------------83935555814334632461054528816 Content-Disposition: form-data; name="_csrf" 41f3dc0a-b97f-4dac-bc49-21e02be53818 -----------------------------83935555814334632461054528816-- 

我通过遵循Spring Security 3.2,CSRF和多部分请求 的接受答案的第二点中的一般建议来修复此问题 ,但使用Spring Security 4.0.1.RELEASE而不是版本3.2。

改变1

将Web应用程序从Servlet API 2.4更新为Servlet API 3.0 :

   ....  

改变2

使用基于Java的配置,创建了一个StandardServletMultipartResolver ,它使用Servlet 3.0的多部分处理,不需要commons-fileupload 。 请注意,原始实现忽略了显式创建任何多部分解析器,尽管它确实包含Maven项目中的依赖commons-fileupload

 @Configuration public class WebApplicationConfiguration { @Bean public MultipartResolver multipartResolver() { return new StandardServletMultipartResolver(); } } 

改变3

DispatcherServlet添加了“multipart-config”:

web.xml

  spring-web org.springframework.web.servlet.DispatcherServlet 1  /tmp 1000000 1000000 10000   

使用Java:

 public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { public SecurityWebApplicationInitializer() { super(SecurityConfiguration.class); } @Override protected void beforeSpringSecurityFilterChain(ServletContext servletContext) { final XmlWebApplicationContext appContext = new XmlWebApplicationContext(); appContext.setConfigLocation("/WEB-INF/spring-web-servlet.xml"); final ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher", new DispatcherServlet(appContext)); registration.setLoadOnStartup(1); registration.addMapping("/"); registration.setMultipartConfig(new MultipartConfigElement("", 1000000, 1000000, 100000)); } } 

改变4

从Maven项目中删除了依赖项commons-fileupload