Notes: CORS, the thing you wish you could ignore

It’s 2016, and that means security… even if it’s just sandboxing.

Modern web browsers implement a protocol called CORS, i.e. Cross-Origin Resource Sharing. This is a fancy protocol that gives a web browser hints that a transaction should be allowed or not. It was a few years ago that for the sake of security, browsers switched from trusting every request to trusting no request. For the sake of compatibility, some requests are still honoured (HEAD, GET, POST with specific content-types), but some of the most useful ones are not.

Combined with Fetch, the modern/correct way to fetch data from the internet in current browsers (previously XmlHttpRequest), this can messy. But hey, it’s for the greater good… I guess.

Fetch, Promises and Lambda Arrow Functions

JavaScript’s new Fetch method is the recommended way to handle what we used to call “XHR” requests (i.e. getting data by URL) for any new code that’s written. It’s supported by all the major current browsers, and can be polyfilled for backwards compatibility.

The old way (“XHR”) was inelegant, and poorly named (XML HTTP Request). Fetch has a much improved syntax.

Fetch relies on another modern JavaScript feature: Promises. Promises let you wire up code that can be run asynchronously immediately after (in this case) the Fetch completes, be it a success or failure. As with Fetch, this can be introduced in older browsers with a Polyfill.

Furthermore, Promises benefit from another modern JavaScript feature: Lambda Functions or Arrow Functions as they’re sometimes called. In essense, this a new syntax for creating functions in JavaScript. Unlike Fetch and Promises, Lambda Functions cannot be added to JavaScript with a Polyfill. They require a modern JavaScript compiler (or transpiler) to add them in a compatible way.

1

2

3

4

5

6

7

8

9

10

# Normal Syntax

varMyFunc=function(arg){returnarg+arg;}

# Lambda/Arrow Function Syntax

varMyFunc=arg=>arg+arg;// Exactly the same. Function returns arg+arg

# Variants

varMyFunc=arg=>{returnarg+arg;};// You can be more verbose

varMyFunc=(arg1,arg2)=>arg1+arg2;// Pass Multiple Arguments

varMyFunc=()=>{console.log('hey');return25;}// No Arguments, do multiple things

And at the time of this writing, Rest Destructuring is starting to pop up as a feature (currently unsupported in Buble, without a patch… a patch that exists, and is one click away from being merged in, tee hee).

Legacy Fetch Support

We can do a number of things without worring about Preflights or Cookies, but we still need a CORS header (Access-Control-Allow-Origin). These also work if the origin (protocol+domain) is the same, but CORS is the whole mess when origins (protocol+domain) differ.

1

2

3

4

5

6

# HTTP GET

fetch("http://blah.com/file");

fetch("http://blah.com/file",{method:'GET'});

# HTTP HEAD

fetch("http://blah.com/file",{method:'HEAD'});

You can also do HTTP POST, but when we start talking HTTP POST, we need to start caring about content-type.

In legacy mode, HTTP POST only supports 3 different content types.

text/plain

multipart/form-data

application/x-www-form-urlencoded

That doesn’t mean you can’t use other content-types, but it introduces a new “feature” that we’ll get to soon.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

# NOTE: PHP routes the body to php://stdin, and not $_POST

fetch("http://blah.com/file",{

method:'POST',

headers:{

'Content-Type':'text/plain',

},

body:"hello world"

})

# I wasn't able to get multipart/form-data woring easily (responses are weird looking)

# This however will populate $_POST with data

vardata={

a:10,

b:true,

c:"stringy"

};

fetch("http://blah.com/file",{

method:'POST',

headers:{

'Content-Type':'application/x-www-form-urlencoded',

},

body:Object.keys(data).map((key)=>{

returnencodeURIComponent(key)+'='+encodeURIComponent(data[key]);

}).join('&')

})

Bypassing CORS

There is a mode you can set…

1

2

3

4

5

6

7

8

fetch("http://blah.com/file",{

method:'POST',

headers:{

'Content-Type':'text/plain',

'mode':'no-cors'

},

body:"hello world"

})

But this is effectively the same as a HEAD request. It will correctly pass (.then) or fail (.catch) depending on the response code, but you can’t look at data.

Anyways, I think I’ve suffered through CORS enough now. Like always, this post is here so when I have to revisit the topic (uploads), I’ll know where to start (configure server to Allow-Origin: * (i.e. readonly GET requests), but get specific in the PHP upload script so that credentials matter (PUT/POST)). (PS: I could stop hot-linking if Allow-Origin was specific to Jammer sites).

This entry was posted
on Saturday, November 19th, 2016 at 4:33 AM and is filed under Uncategorized.
You can follow any responses to this entry through the RSS 2.0 feed.
Both comments and pings are currently closed.