Spring CSRF 多部分文件上传

Posted

技术标签:

【中文标题】Spring CSRF 多部分文件上传【英文标题】:Spring CSRF Mutltipart File Upload 【发布时间】:2017-11-05 17:28:17 【问题描述】:

我遵循了这个指南:

http://docs.spring.io/spring-security/site/docs/4.2.2.RELEASE/reference/htmlsingle/#csrf-multipartfilter?

http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-multipart

在我的 spring mvc 项目上设置文件上传,但出现此错误:

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.

我的 web.xml(完整)

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <multipart-config>
        <location>/tmp</location>
        <max-file-size>1000000</max-file-size>
        <max-request-size>1000000</max-request-size>
        <file-size-threshold>10000</file-size-threshold>
    </multipart-config>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/appServlet/spring-security.xml,
            /WEB-INF/spring/appServlet/spring-datasource.xml
        </param-value>
    </context-param> 

    <!-- Spring Security  Filter -->
    <filter>
        <filter-name>MultipartFilter</filter-name>
        <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
    </filter>
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MultipartFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

Spring servlet 内容(完整)

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <beans:bean id="multipartResolver"
        class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
    </beans:bean>

    <context:component-scan base-package="com.at.ccts.controller" />

 </beans:beans>

jsp

        <h1>Please upload a file</h1>
    <form method="post" action="$pageContext.request.contextPath/create/form" enctype="multipart/form-data">
        <input type="text" name="name"/>
        <input type="file" name="file"/>
        <input type="submit"/>
    </form> 

控制器

@RequestMapping(value = "/form", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("name") String name,
    @RequestParam("file") MultipartFile file) 

    if (!file.isEmpty()) 
        try 
            byte[] bytes = file.getBytes();
         catch (IOException e) 
            // TODO Auto-generated catch block
            e.printStackTrace();
        
        // store the bytes somewhere
       return "redirect:uploadSuccess";
    else 
       return "redirect:uploadFailure";
   

有人知道为什么它仍然要求令牌吗?

【问题讨论】:

你试过Spring表单标签库吗? 将表单更改为 form:form 解决了该问题。谢谢。 【参考方案1】:

默认情况下,Spring Security 现在在所有“修改”请求(POST、DELETE 等)上都需要 CSRF 令牌。为了更轻松地处理 CSRF,您可以使用 Spring taglibs(用于 JSP)或 Spring Security 方言(用于 Thymeleaf)。对于 JSP,您只需将表单编写为

<form:form ...>

taglib 会为你插入一个带有 CSRF 令牌的&lt;input type="hidden"&gt;

【讨论】:

以上是关于Spring CSRF 多部分文件上传的主要内容,如果未能解决你的问题,请参考以下文章

Struts2 中的文件上传以及 Spring CSRF 令牌

使用 Spring 上传多部分文件:NoSuchMethodException: ...CommonsMultipartFile.<init>()

如何使用多部分/表单和分块编码在 spring mvc 中接收文件上传?

Spring认证指南:了解如何构建一个多文件上传的 Spring 应用程序

当前请求不是多部分请求 Spring Boot 和 Postman(上传 json 文件加上额外字段)

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