DOMjudge / domjudge

DOMjudge programming contest jury system
https://www.domjudge.org
GNU General Public License v2.0
701 stars 249 forks source link

Enable Cross-Origin Resource Sharing (CORS) for DOMjudge API Service #2504

Closed jimmyhealer closed 2 months ago

jimmyhealer commented 2 months ago

Description of the enhancement request

Let's add CORS headers to the DOMjudge API so any host can hit it up. This would get rid of those annoying cross-origin issues and make the API way more user-friendly for devs working from different domains.

The goal you want to achieve

The main aim here is to make the DOMjudge API super accessible for everyone out there trying to integrate or mess around with it from wherever they are. By throwing in CORS headers, we’re talking about boosting collaborations and making it a breeze for other tools and apps to interact with our stuff. It’s all about making DOMjudge more versatile and widely usable in the dev community and beyond.

Expected behaviour

Here’s how things should go down with the new CORS setup:

nickygerritsen commented 2 months ago

It seems https://github.com/nelmio/NelmioCorsBundle can do this for us.

nickygerritsen commented 2 months ago

We do set Access-Control-Allow-Origin to * already, see https://github.com/DOMjudge/domjudge/blob/main/webapp/src/EventListener/ApiHeadersListener.php#L18-L18. @jimmyhealer what did not work for you? We might need to set allowed methods or something related.

jimmyhealer commented 2 months ago

Oh, I originally thought I hadn't set Access-Control-Allow-Origin to *. But looking closely at the Header, it does include that, but I still get the following error: Access to fetch at 'http://other.domjudge.com/api/v4/contests?onlyActive=false' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I guess I should add the following content, because it is a preflight request that cannot pass the access control check before:

// If the request method is OPTIONS, handle preflight request.
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH');
  $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  $response->setStatusCode(204); 
}
nickygerritsen commented 2 months ago

Yeah I expected something like this. Let's use that bundle then to fix this.