使用 PDF.js 查看器显示受保护资源提供的 pdf

Using PDF.js viewer to display a pdf served by a protected resource

我正在研究如何使用 pdfjs 查看器来提供受保护资源背后的 PDF。

据我了解,如果资源允许匿名访问,这将有效: https://app.com/pdf.js/web/viewer.html?file=https://app.com/pdf/{id}

资源 https://app.com/pdf/{id} returns 内容类型为 application/pdf 的响应。

但是,该资源需要 OAuth2 令牌出现在授权中 header。 那么是否可以修改查看器创建的 headers,以包含授权 header 并传递用户的令牌?

PDF.js可以读取Base64格式的文件(example)。因此,您可以使用 Ajax / HTTP 客户端下载授权 header 的二进制数据,转换为 Base64 字符串,然后嵌入到 PDF

编辑:您可以将 HTTP headers 设置为 PDF getDocument 功能。所以您可以将访问令牌存储在 Web 存储中,然后在 pdf 查看器的页面中获取它

var loadingTask = pdfjsLib.getDocument({
  url,
  withCredentials,
  httpHeaders: {
    authentication: "abcxyz",
  }
});