Sunday, 23 January 2011

Resolving the HTTP/HTTPS “Document contains both secure/unsecure content” message

One of the most commonly encountered issues when developing websites that must support both HTTP and HTTPS pages is the warning that a secure page “contains both secure and unsecure content”. In a nutshell this is when a page that is being displayed via the HTTPS protocol contains one or more references to additional resources (JS/CSS/Images) using just HTTP.

The solution is easy and well documented for locally referenced resources, in that when making the reference to the required file you exclude the protocol and domain name ending up with something like “/styles/main.css”, which will quite happily call “main.css” from a “styles” folder in the root of the web application regardless of whether the containing page is being called by HTTP or HTTPS.

Note: .NET provides functionality such as ResolveUrl(“~/styles/main.css”) which should always be used in preference to hard coded paths such as “/styles/main.css”. Using ResolveUrl(…) will work regardless whether in IIS the web application has been set up as a website or a child application of the parent website. However the hardcoded path will always default to the root of the website, so if your web application has been deployed within IIS as a child application of a website you will typically see lots of 404’s as the browser is unable to locate the resources using the URL provided.

Typically externally referenced resources have proved more troublesome. I’ve seen quick and dirty solutions that always call external references via HTTPS. This gets around the warning when viewing the calling page in HTTPS, but introduces additional processing/overheads when viewing the referencing page in HTTP. More typically the URL for the required external resource is passed to a helper functional which determines which protocol to add depending upon whether the containing page is HTTP or HTTPS.

But it would appear that all the solutions for resolving the protocol for externally referenced resources were over-engineered! Under the section A Better Solution, Dave Ward provides a solution that is pretty much identical to the tried and tested internally referenced resource solution. Basically the RFC 3986 spec allows resources to be referenced using a protocol-less format. So instead of worrying whether you should be calling “http://cdn.domain/common-resouce.js” or “https://cdn.domain/common-resouce.js”, you can just call “//cdn.domain/common-resouce.js” and the protocol to be used for the external reference is determined by the protocol context of the containing page! Thanks for highlighting this Dave, much easier!

No comments:

Post a Comment