I have a console app (that will ultimately run as a worker in Azure) that requests a page from my main ASP.Net MVC site, and converts it to a PDF. That site is secured by forms authentication.
In the code that requests the page, I pass in an HttpContext that contains a valid forms authentication cookie:
byte[] pdfBytes = PdfHelper.UrlToPdfBytes(url, new HttpContextWrapper(GetHttpContext(url)));
And the GetHttpContext method:
private static HttpContext GetHttpContext(string url)
{
var stringWriter = new StringWriter();
var httpRequest = new HttpRequest("", url, "");
var httpResponse = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponse);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
2,
"remoteuser",
DateTime.Now,
DateTime.Now.AddMinutes(5),
false,
String.Empty,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
{
HttpOnly = true//,
//Domain = new Uri(url).Host
};
httpRequest.Cookies.Add(cookie);
return httpContext;
}
No matter what I try, though, the resulting PDF always contains the login form - the authentication cookie is seemingly ignored.
The cookie names are the same, and the values inside match those of the cookie that exists in the browser, yet I can't get it to work.
The attributes on my controller actions don't even get hit (I have one that ensures the logged in user can access the data being requested), which suggests that it's IIS that is throwing the request to the login form (via the settings in web.config).
I got the request to work by adding the AllowAnonymous attribute on the controller, so I know the request itself works as expected, but I can not get the FormsAuthentication aspect working. I'm only working locally in VS2017 at the moment, using IIS (not IIS Express).
I've set breakpoints in the PDFHelper.UrlToPdfBytes method, and the cookie is there (and the ticket decrypts correctly).
This has been frustrating me for days now, so any help is appreciated.