3

I have seen in many places that one of the benefits of token-based authentication over cookie-based authentication is it is better suite for CORS/cross-domain scenario.

But why?

Here is a CORS scenario:

An HTML page served from http://domain-a.com makes an <img> src request for http://domain-b.com/image.jpg.

Even if there's a token on my machine, how could the mere <img> tag know where to find and send it?

And according to here, it is suggested to store JWT as cookie, so how could that survive the CORS/cross-domain scenario?

ADD 1

Token-based authentication is easier to scale out than session-cookie one. See a related thread here: Stateless web application, an urban legend?

Community
  • 1
  • 1
smwikipedia
  • 61,609
  • 92
  • 309
  • 482

1 Answers1

2

Just for clarification: Requests to any subdomain that you have are also considered as cross origin request (ex. you make request from www.example.com to api.example.com).

A simple <img> GET request to another origin is, indeed, cross origin request as well, but browsers are not using preflighted (OPTION) requests if you use GET, HEAD, POST requests only, and your Content-Type header is one of the followings:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

Therefore simple <img> request to another origin won't have problem (regardless if subdomain or totally another domain), as it won't go through preflight, unless it requires credentials, because when you add Authorization header, the request needs to go through preflight.

About storing in localstorage vs in cookie: Localstorage has single origin policy, meaning you cannot access the data you have stored from the subdomain, ie, example.com cannot access data in localstorage of api.example.com. On the other hand, using cookies, you can define which subdomains can access to the cookie. So you can access your token in stored in cookie and send it to server with your requests. Cookies also doesn't allow to access data across different domains.

Hope this helps.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Ahmet Cetin
  • 3,683
  • 3
  • 25
  • 34