I was checking a number of URL endpoints for CORS restrictions today and I wondered if I could check from the command line. Here are some example curl
statement that get me the information I’m looking for. I think there is an opportunity for a custom function here but for now, these notes will do.
Example With No Restrictions
Since the access-control-allow-origin
value is *
, any site is allowed.
curl -I -H "Origin: https://salcode.test" \
--verbose 'https://api.weather.gov/gridpoints/TOP/31,80/forecast' \
2>&1 | grep -i 'access-control-allow-origin:'
Result
< access-control-allow-origin: *
access-control-allow-origin: *
Example with Approving Origin Site
Whatever Origin
value is sent as a header is also returned as the access-control-allow-origin
value.
As long as the correct Origin
value is sent as a header, the requesting site is allowed.
curl -I -H "Origin: https://salcode.test" \
--verbose 'https://salferrarello.com/wp-json/wp/v2/posts/' \
2>&1 | grep -i 'access-control-allow-origin:'
Result
< access-control-allow-origin: https://salcode.test
access-control-allow-origin: https://salcode.test
Example With Default Restrictions
When no access-control-allow-origin
value is returned, the default CORS restrictions are in place. Only the site (www.bcferriesapi.ca
) is allowed.
curl -I -H "Origin: https://salcode.test" \
--verbose 'https://www.bcferriesapi.ca/api/tsawwassen/' \
2>&1 | grep -i 'access-control-allow-origin:'
No Result
JavaScript
Another related trick I use to check for CORS is running a fetch() of the URL in the browser console.
With CORS Restrictions
With CORS restrictions, the fetch()
will fail.
await fetch('https://www.bcferriesapi.ca/api/tsawwassen/')
Without CORS Restrictions
Without CORS restrictions, the fetch()
will successfully return a response.
await fetch('https://api.weather.gov/gridpoints/TOP/31,80/forecast')
Leave a Reply