Here's my issue. My server is configured for CORS and the preflight request works fine:
$> curl 'https://db.mywebsite.com/something/_search' -X 'OPTIONS' ...
< HTTP/1.1 200 OK
< Access-Control-Allow-Origin: *
< Allow: GET,POST
< Content-Length: 0
< Content-Type: text/plain; charset=UTF-8
< Date: Tue, 20 Apr 2021 06:18:36 GMT
As you can see, it is set up to allow every origin (since allowing the proper origin did not work I tried with *
and the problem persists.)
When making the subsequent actual request though, here is what I'm getting:
$> curl 'https://db.mywebsite.com/something/_search' -X 'POST' -H 'origin: https://mywebsite.com/' ...
< HTTP/1.1 403 Forbidden
< Access-Control-Allow-Origin: *
< Content-Length: 0
< Date: Tue, 20 Apr 2021 06:20:02 GMT
And interestingly, if I remove the origin
header, it works fine, so this rules out that the 403 would come from the backend server.
When I look for similar problems online I only end up on cases where the preflight requests get 403s but I couldn't find anything similar to what I'm facing here. Any idea what it could be due to?
It turns out the issue was not what I had imagined and couldn't have possibly been figured out by just looking at the information I posted initially. In case that ever helps anyone though, what happened is the following:
The database is ElasticSearch and it was configured to enable CORS with the following configuration:
http:
cors:
enabled: true
allow-credentials: true
allow-origin: "https://mywebsite.com"
allow-headers: "X-Requested-With, Content-Type, Content-Length, Authorization"
allow-methods: "PUT, OPTIONS, POST"
And at the sane time, it was served by Traefik, which was also configured to answer with CORS headers:
elasticsearch:
image: elasticsearch:7.12.0
labels:
- "traefik.enable=true"
- "traefik.http.middlewares.addAuth.headers.accesscontrolallowmethods=PUT, OPTIONS, POST"
- "traefik.http.middlewares.addAuth.headers.accesscontrolalloworiginlist=https://mywebsite.com"
- "traefik.http.middlewares.addAuth.headers.accesscontrolallowheaders=X-Requested-With, Content-Type, Content-Length, Authorization"
- "traefik.http.routers.db.middlewares=addAuth"
- "traefik.http.routers.db.rule=Host(`db.mywebsite.com`)"
- "traefik.http.routers.db.tls=true"
- "traefik.http.routers.db.tls.certresolver=myresolver"
- "traefik.port=9200"
And it turns out that having both configurations running at the same time, Traefik handles the preflight request just fine, forwards the actual request, and ElasticSearch then rejects it.
Simply removing the CORS configuration in ElasticSearch and relying on Traefik instead solved the issue.