0

Working with NReco.PdfGenerator.HtmltoPdfConverter and recently implemented OAuth with Bearer tokens. After implementing and securing my ApiControllers the converter started throwing the following error.

WkHtmlToPdfException: Exit with code 1 due to network error: AuthenticationRequiredError (exit code: 1)

After some snooping I discovered I could add custom header parameters and so I grabbed the bearer token and appended it to the CustomWkHtmlArgs

This is what I have to far.

        htmlToPdf.CustomWkHtmlArgs = "-L 0mm -R 0mm -T 5mm -B 0mm --javascript-delay 3000";

        FileHandlingModule.deleteFile(savePath);

        //Get Auth Token
        var accessToken = "Bearer " + Request.Headers.Authorization.Parameter;

        htmlToPdf.CustomWkHtmlArgs += " --custom-header Authorization: " + accessToken;
        htmlToPdf.GeneratePdfFromFile(purl, null, savePath);

This is what the CustomWkHtmlArgs this is what the args string look like.

-L 0mm -R 0mm -T 5mm -B 0mm --javascript-delay 3000 --custom-header Authorization: Bearer YHE7HJEh_Hk0wazErUK6DIGcCG7-GRDHBEWRA-ju9hewqPk9cjY3zH5MT....

The token has been shortened for brevity. I've tried removing the colon and I still get the AuthRequiredError. Is anyone familiar with passing header auth tokens?

Vitaliy Fedorchenko
  • 8,447
  • 3
  • 37
  • 34
Jeremy Bond
  • 159
  • 1
  • 15

1 Answers1

0

First of all try to pass header value in quotes:

htmlToPdf.CustomWkHtmlArgs += " --custom-header \"Authorization\" \"" + accessToken + "\"";

If this header is needed to access page resources (images, css, ajax calls) option "--custom-header-propagation" should be specified too.

BTW, have you tried your to test your custom header with wkhtmltopdf from the command line? Also, you can handle htmlToPdf.LogReceived event and get wkhtmltopdf console log output - it might be useful for debug purposes.

Vitaliy Fedorchenko
  • 8,447
  • 3
  • 37
  • 34
  • Thanks for the tip about the command line. That helped expedite the troubleshooting process. Two things to note. Wrap the token in quotes, not the entire http header parameter ' htmlToPdf.CustomWkHtmlArgs += " --custom-header Authorization \"" + accessToken + "\"";' If page the contains additional AJAX calls that are secured you'll also need to add the switch _--custom-header-propagation_ . This instructs wkhtmltopdf to add the header object to each subsequent call. – Jeremy Bond Nov 29 '17 at 20:32