Tuesday, February 24, 2015

Gotcha of the Day: CORS Requests fail when switching to an HTTPs Environment

Tonight I was migrating a client's site from HTTP to HTTPs when I ran into this conundrum: when I updated www.foo.com to invoke api.foo.com over HTTPs I started getting CORS related errors in Firebug:

This is confusing because api.foo.com was and is setup to return back the appropriate CORS related headers. Surely CORS isn't supposed to just break when you switch to HTTPs, is it?

I checked and double checked the various CORS headers. Then I came across this notation in the specification:

The term user credentials for the purposes of this specification means cookies, HTTP authentication, and client-side SSL certificates that would be sent based on the user agent's previous interactions with the origin.

Perhaps by switching to HTTPs I now needed to follow the instructions related to user credentials including:

If the resource supports credentials add a single Access-Control-Allow-Origin header, with the value of the Origin header as value, and add a single Access-Control-Allow-Credentials header with the case-sensitive string "true" as value.

Otherwise, add a single Access-Control-Allow-Origin header, with either the value of the Origin header or the string "*" as value.

The string "*" cannot be used for a resource that supports credentials.

Alas, making sure that Access-Control-Allow-Origin was set to the exact value of Origin and sending Access-Control-Allow-Credentials: true made no difference.

Finally, through little more than dumb luck I visited https://api.foo.com in my browser. I'm working in a dev environment, so no big surprise, I got the usual Certificate warning:

Naturally, I accepted the certificate.

And to my complete shock and amazement, the problem was fixed!

This kind of sort of makes sense. I can see why Firefox wouldn't allow CORS requests from a certificate that wasn't (a) valid or (b) added to the exception list. But man, they could have saved me quite a headache if they had somehow indicated the issue in Firebug. At the end of the day, this wasn't really a CORS issue in that CORS was perfectly setup.

No comments:

Post a Comment