Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing CORS with the Postman tool/ cURL/ in Chrome console

I'm testing CORS with the Postman tool and I constantly get

access-control-allow-origin → null

for GET or OPTIONS requests to

http://localhost:4000/api/accounts?Host=http://localhost:4200/&X-Origin=http://jquery.com

Also using Origin instead of X-Origin doesn't change the outcome. Meanwhile, if I use cURL like this

 curl -H "Origin: http://jquery.com" --verbose http://localhost:4000/api/accounts

I do gain access to the API

< access-control-allow-origin: http://jquery.com

I've also opened the jQuery website using http and the chrome Javascript console in order to execute this code:

$.get("http://localhost:4000/api/accounts").then(function(val){console.log(val);})

And it printed the JSON object returned by the API.

Now my questions are as follows:

  1. How can I properly test CORS using Postman? I've noticed that when set the allow origins option on the server to * Postman does return

    access-control-allow-origin → *

The problem mentioned above appears only when I explicitly allow a set of origins like:

`origin: ["https://www.getpostman.com/", "http://localhost:4200/", "http://jquery.com"]`
  1. I noticed that allowing http://jquery.com/ instead of http://jquery.com will not allow requests from which the origin is Origin=http://jquery.com?
  2. I've noticed that cURL returns the contents of the resource (in this case JSON data) even if the request comes from non-authorized origin. Is this normal or does it mean that I forgot to configure something on the server that exposes this data?
like image 987
user3790827 Avatar asked Jun 29 '16 15:06

user3790827


2 Answers

You can try

curl -X OPTIONS 'https://domain/path/file.png' -H "Origin: https://yoursitedomain" -H "Access-Control-Request-Method: GET" -v -o /dev/null
like image 125
David Kochkerian Avatar answered Sep 27 '22 21:09

David Kochkerian


The Origin header sent from the client is the scheme, domain and port (if not 80), from which the request originates. The trailing / is not valid in the header. You cannot send multiple origins either. The Access-Control-Allow-Origin sent from the server can either be *, allowing all origins, or you send back the same origin from the request header.

For example, if you make a request to http://www.telerik.com/ in Chrome, the request header contains Origin:http://www.telerik.com (the browser automatically sends this), and the response header from the server contains Access-Control-Allow-Origin:http://www.telerik.com.

As for your last question, according to the specification, the user agent is responsible for enforcing CORS, so I suspect cURL doesn't validate that the request and response match.

The user agent validates that the value and origin of where the request originated match.

Source: https://www.w3.org/TR/cors/

like image 21
Gideon Pyzer Avatar answered Sep 27 '22 21:09

Gideon Pyzer