Pdf.js: How to add custom header?

Created on 27 Oct 2013  路  6Comments  路  Source: mozilla/pdf.js

Hello,

My web application requires a custom header for authetication, how can I pass this header in request?

Most helpful comment

@yurydelendik I would be nice to have an example. I tried something like this but with no success:

PDFJS.getDocument({
  url: this.docUrl,
  httpHeaders: { Authorization: `Bearer ${getAuthenticationToken()}` },
  withCredentials: true,
})

All 6 comments

Check https://github.com/mozilla/pdf.js/blob/master/src/display/api.js#L99 , getDocument has ability to pass custom headers.

Thank you @yurydelendik

@yurydelendik Do you have an example on how to configure the httpHeaders?

@yurydelendik I would be nice to have an example. I tried something like this but with no success:

PDFJS.getDocument({
  url: this.docUrl,
  httpHeaders: { Authorization: `Bearer ${getAuthenticationToken()}` },
  withCredentials: true,
})

@siegy22 @bierik please provide complete example, the example below (based on the comment above) works for me:

diff --git a/examples/helloworld/hello.js b/examples/helloworld/hello.js
index fe413c77..538e7a03 100644
--- a/examples/helloworld/hello.js
+++ b/examples/helloworld/hello.js
@@ -13,7 +13,11 @@ Promise.all([System.import('pdfjs/display/api'),
   global.PDFJS.workerSrc = modules[3];

   // Fetch the PDF document from the URL using promises.
-  api.getDocument('helloworld.pdf').then(function (pdf) {
+  api.getDocument({
+    url: 'helloworld.pdf',
+    httpHeaders: { Authorization: 'Fail' },
+    withCredentials: true,
+  }).then(function (pdf) {
     // Fetch the page.
     pdf.getPage(1).then(function (page) {
       var scale = 1.5;
diff --git a/test/webserver.js b/test/webserver.js
index d5210113..fd328a19 100644
--- a/test/webserver.js
+++ b/test/webserver.js
@@ -143,6 +143,16 @@ WebServer.prototype = {
         return;
       }

+      var auth = req.headers['authorization'];
+      if (auth) {
+        console.log(auth);
+        if (auth === 'Fail') {
+          res.writeHead(444);
+          res.end('Fail', 'utf8');
+          return;
+        }
+      }
+
       var range = req.headers['range'];
       if (range && !disableRangeRequests) {
         var rangesMatches = /^bytes=(\d+)\-(\d+)?/.exec(range);

Below invoke worked for me smooth!

var loadingTask = pdfjs.getDocument({
url: pdf_url,
httpHeaders: { 'Access-Key': myKey },
withCredentials: true,
});

Was this page helpful?
0 / 5 - 0 ratings

Related issues

timvandermeij picture timvandermeij  路  4Comments

sujit-baniya picture sujit-baniya  路  3Comments

zerr0s picture zerr0s  路  3Comments

jigskpatel picture jigskpatel  路  3Comments

THausherr picture THausherr  路  3Comments