I'm trying to print out a pdf invoice from a page that requires authentication (https://localhost:44362/invoice
). All of this works neatly when authorization is off, but when I turn it on, the whole thing falls apart. I'm using .NET Core 2.1 MVC with Identity authentication. I've tried two different solutions, which both fail different ways.
Attempt 1:
The rendering works, but the login fails, and the resulting pdf is the login page. This, I understand, is normal behaviour when authentication fails.
var uri = new Uri("https://localhost:44362/invoice");
var newPdf = new HtmlToPdf()
{
PrintOptions = new PdfPrintOptions()
{
//..omitted for brevity
},
LoginCredentials = new HttpLoginCredentials()
{
EnableCookies = true,
LoginFormPostVariables = new Dictionary<string, string>()
{
{ "Email", "username@domain.com" },
{ "Password", "secretysecret" }
},
LoginFormUrl = new Uri("https://localhost:44362/login")
}
};
var result = newPdf.RenderUrlAsPdf(uri);
Attempt 2:
I get the authorization cookie from the original request. This works, at least so far that I can actually get the cookie and set it to the LoginCredentials.CustomCookies
. I've compared it with the browser request, and the cookie seems to be correct. The collection Request.Cookies
holds two cookies, one Antiforgery, and one for Identity.
The rendering fails, because newPdf.RenderUrlAsPdf(uri)
returns null
and I don't understand why. The reason must be with the CustomCookies
set in the LoginCredentials
failing somehow, but the stack trace doesn't give any information about what fails. Just to be clear, this method fails even when the authorization is not in use.
var uri = new Uri("https://localhost:44362/invoice");
var cookies = Request.Cookies;
Dictionary<string, string> customCookies = cookies.ToDictionary(c => c.Key, c => c.Value);
var newPdf = new HtmlToPdf()
{
PrintOptions = new PdfPrintOptions()
{
//..omitted for brevity
},
LoginCredentials = new HttpLoginCredentials()
{
EnableCookies = true,
CustomCookies = customCookies
//LoginFormPostVariables = new Dictionary<string, string>()
//{
// { "Email", "username@domain.com" },
// { "Password", "secretysecret" }
//},
//LoginFormUrl = new Uri("https://localhost:44362/login")
}
};
var result = newPdf.RenderUrlAsPdf(uri);