Settling with CORS
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos.[1]
I usually encounter this issue every now and then. Sometimes it can be fixed on my end while other times it's fixed on the developer's end. It could get problematic if future maintainers do not know where it is configured. There are three possible ways where CORS can be configuered, namely through
- Service Provider
- HTTP Server
- Application
Service Provider could mean it can be configured over the management consoles of, i.e. AWS, Azure, GCP, and among others. HTTP Servers such as Nginx and Apache. And lastly through the application. How it implemented will depend on how the infrastructure is architected.
Whenever possible I would recommend in configuring it through the service provider. This would leave out the burden for system administrators or developers in having to do it on their end. If that's not possible, the HTTP server will then suffice. Only do it inthe application as a last resort or by the limitation of not doing it through the other two.
Service Provider
Documentation for configuring CORS in AWS's console can be found here. It comes with two options, enabling it over GUI in the console or enabling it with OpenAPI definition.
HTTP Server
Configuring it in Nginx will fall into the location
block.
location / {
add_header "Access-Control-Allow-Origin" * always;
add_header "Access-Control-Allow-Credentials" *;
add_header "Access-Control-Allow-Methods" *;
add_header "Access-Control-Allow-Headers" *;
proxy_set_header HOST $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://upstream;
}
Application
Probably the easiest to integrate it is through the application itself. I'll be using flask
in this article.
Install Flask-CORS with pip install flask-cors
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
Final Thoughts
From the examples above, it is recommended to limit the origin only through the domain in which it is needed. And I hope that you dear reader may have an idea on how to properly architect your APIs with this read.
Resources
1: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing