为什么将 CONTENT_DISPOSITION 头标记为不安全?

huangapple go评论107阅读模式
英文:

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 = &quot;/export-zip&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity&lt;byte[]&gt; exportZipFile() throws IOException {
		try {
			MyZipObject zip = zipService.createZip();
			HttpHeaders httpHeaders = new HttpHeaders();
			httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, &quot;attachment; filename=\&quot;&quot; + zip.getFileName() + &quot;.zip\&quot;&quot;);
			return new ResponseEntity&lt;&gt;(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&quot;

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, &quot;attachment; filename=\&quot;&quot; + fileName + &quot;.zip\&quot;&quot;);

huangapple
  • 本文由 发表于 2020年7月22日 19:35:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63033258.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定