Skip to content

Instantly share code, notes, and snippets.

@vlazic
Last active June 23, 2022 12:00
Show Gist options
  • Save vlazic/9807583e155560d2917bebb8ff99cd9f to your computer and use it in GitHub Desktop.
Save vlazic/9807583e155560d2917bebb8ff99cd9f to your computer and use it in GitHub Desktop.
Test CORS access with cURL

Test CORS access with cURL

What is it?

This script is a simple tool to test if server allows cross-origin resource sharing (CORS), i.e. if server allows requests from some domain.

Installation

Download script to ~/.local/bin/cors_test.sh

wget -P ~/.local/bin https://gist.githubusercontent.com/vlazic/9807583e155560d2917bebb8ff99cd9f/raw/e22e82e84f38437bd85b6f8aa09bb172eeb8e439/cors_test.sh
chmod +x ~/.local/bin/cors_test.sh

Usage

You can use this script as a standalone tool.

There are two arguments:

  1. Origin of request (frontend app)
  2. Destination url (server)
cors_test.sh http://localhost https://example.com

License

MIT

#!/usr/bin/env bash
# Cross-Origin Resource Sharing (CORS) test script
# this script tests if server ($1) allows access from specific website ($2)
#
# installation:
# wget -P ~/.local/bin https://gist.githubusercontent.com/vlazic/9807583e155560d2917bebb8ff99cd9f/raw/e22e82e84f38437bd85b6f8aa09bb172eeb8e439/cors_test.sh ; chmod +x ~/.local/bin/cors_test.sh
#
# function expects two arguments:
# 1) origin of request (frontend app)
# 2) destination url (server)
#
# example:
# ./cors_test.sh http://localhost https://example.com
#
# --verbose :
# Prints the server response headers.
# --request OPTIONS :
# Specifies the HTTP method to use for the request.
# --header "Origin: ${1}" :
# Specifies the origin of the request.
# --header 'Access-Control-Request-Method: GET' :
# Specifies the method to use for the actual request.
# 2>&1 | grep -i 'Access-Control-Allow-Origin' :
# grep is used to find the header that indicates whether the server permits cross-origin resource sharing with resource
if curl \
--verbose \
--request OPTIONS \
"$2" \
--header "Origin: ${1}" \
--header 'Access-Control-Request-Method: GET' 2>&1 |
grep -qi 'Access-Control-Allow-Origin'; then
echo "👍 ${2} allows CORS requests from ${1}"
else
echo "👎 ${2} does not allow CORS requests from ${1}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment