此文件包含上传文件的表单
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>
和我的控制器方法是
@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.";
}
}
上传时出现以下错误:
HTTP状态403 - 无效的CSRF令牌&#39; null&#39;在请求参数&#39; _csrf&#39;上找到或标题&#39; X-CSRF-TOKEN&#39;
我也使用过弹簧安全装置。但我总是给出同样的错误。我尝试了很多,但无法解决它。你能帮忙解决这个问题。
答案 0 :(得分:4)
看起来您的Spring应用程序中的CSRF(跨站点请求伪造)保护已启用。实际上它是默认启用的。
根据spring.io:
什么时候应该使用CSRF保护?我们的建议是使用CSRF 保护浏览器可以处理的任何请求 普通用户。如果您只是创建使用的服务 非浏览器客户端,您可能希望禁用CSRF保护。
所以要禁用它:
@Configuration
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
如果您希望启用CSRF保护,则必须在表单中加入csrftoken
。你可以这样做:
<form .... >
....other fields here....
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
您甚至可以在表单的操作中包含CSRF令牌:
<form action="./upload?${_csrf.parameterName}=${_csrf.token}" method="post" enctype="multipart/form-data">