简体   繁体   English

上传时出现HTTP 403错误 - 无效的CSRF令牌'null'

[英]HTTP 403 error while upload - Invalid CSRF Token 'null'

this file contains a form to upload a file 此文件包含上载文件的表单

uploadForm.jsp uploadForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"   pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<sec:csrfMetaTags/>
<title>File Upload</title>
</head>
<body>
    <jsp:include page="/resources/layout/header.jsp"/>      <!-- Header -->   
        <div class="container">

            <form action="uploadfile" method="POST" enctype="multipart/form-data">              
                    File to upload: <input type="file" name="file"><br /> 
                    Name: <input type="text" name="name"><br /> <br />
                    <input type="submit" value="Upload"> Press here to upload the file!
            </form>
        </div>  <!-- Container -->

        <jsp:include page="/resources/layout/footer.jsp"/>      <!-- Footer -->
</body>
</html>

and My controller method is 我的控制器方法是

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public String uploadFileHandler(@RequestParam("name") String name,@RequestParam("file") MultipartFile file) {

        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();

                // Creating the directory to store file
                String rootPath = System.getProperty("catalina.home");
                File dir = new File(rootPath + File.separator + "tmpFiles");
                if (!dir.exists())
                    dir.mkdirs();

                // Create the file on server
                File serverFile = new File(dir.getAbsolutePath()
                        + File.separator + name);
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();

                logger.info("Server File Location="
                        + serverFile.getAbsolutePath());

                return "You successfully uploaded file=" + name;
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name
                    + " because the file was empty.";
        }
    }

I have the following error on upload : 上传时出现以下错误:

HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN' HTTP状态403 - 在请求参数'_csrf'或标题'X-CSRF-TOKEN'上找到无效的CSRF令牌'null'

I have used spring security also. 我也使用过弹簧安全装置。 But i always give an same error. 但我总是给出同样的错误。 i tried lot but unable to solve it. 我尝试了很多,但无法解决它。 Could you please help to solve this. 你能帮忙解决这个问题吗?

It looks like the CSRF (Cross Site Request Forgery) protection in your Spring application is enabled. 看起来您的Spring应用程序中的CSRF(跨站点请求伪造)保护已启用。 Actually it is enabled by default. 实际上它是默认启用的。

According to spring.io : 根据spring.io

When should you use CSRF protection? 什么时候应该使用CSRF保护? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. 我们的建议是对普通用户可以由浏览器处理的任何请求使用CSRF保护。 If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection. 如果您只创建非浏览器客户端使用的服务,则可能需要禁用CSRF保护。

So to disable it: 所以要禁用它:

@Configuration
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
  }
}

If you want though to keep CSRF protection enabled then you have to include in your form the csrftoken . 如果您希望保持启用CSRF保护,则必须在表单中包含csrftoken You can do it like this: 你可以这样做:

<form .... >
  ....other fields here....
  <input type="hidden"  name="${_csrf.parameterName}"   value="${_csrf.token}"/>
</form>

You can even include the CSRF token in the form's action: 您甚至可以在表单的操作中包含CSRF令牌:

<form action="./upload?${_csrf.parameterName}=${_csrf.token}" method="post" enctype="multipart/form-data">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM