英文:
Why is the CONTENT_DISPOSITION header considered unsafe?
问题
我已经开发了一个REST端点,它产生一个序列化为字节数组的zip文件。
@GetMapping(path = "/export-zip", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<byte[]> exportZipFile() throws IOException {
try {
MyZipObject zip = zipService.createZip();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + zip.getFileName() + ".zip\"");
return new ResponseEntity<>(zip.getData(), httpHeaders, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
使用Postman,我可以成功地从此API获取响应并将其保存为Zip文件。但是,我们前端使用的React代码调用此API时出现错误。
Refused to get unsafe header “Content-Disposition"
我不确定为什么该标头被认为是不安全的,但我也想知道如何将其呈现为安全标头。
英文:
I’ve developed a REST endpoint that produces a zip file serialized to a byte array.
@GetMapping(path = "/export-zip", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<byte[]> exportZipFile() throws IOException {
try {
MyZipObject zip = zipService.createZip();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + zip.getFileName() + ".zip\"");
return new ResponseEntity<>(zip.getData(), httpHeaders, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Using Postman, I can successfully get the response from this API and save it to a Zip file. However the React code that our front-end uses to call this API is producing an error
Refused to get unsafe header “Content-Disposition"
I’m unsure why the header is considered unsafe to begin with but I’d also like to know how I can render it a safe header.
答案1
得分: 3
这是一个有用的回应,谢谢。最后,我通过将以下代码添加到我的控制器中成功修复了这个问题:
httpHeaders.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + ".zip\"");
英文:
That was a useful response, thanks. In the end, I was able to fix this by adding the following code to my controller
httpHeaders.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + ".zip\"");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论