tuupola / cors-middleware

PSR-7 and PSR-15 CORS middleware
MIT License
132 stars 16 forks source link

Core Middleware do not works for me #46

Closed Awilum closed 4 years ago

Awilum commented 4 years ago

I am using Slim3

Here is my code to enable CORS Middleware https://github.com/flextype/flextype/blob/dev/flextype/middlewares.php#L22

and here is my API https://github.com/flextype/flextype/blob/dev/flextype/api/delivery/entries.php#L29

I am testing my API https://flextype.org/api/delivery/entries?id=en&token=1a48b9de0494240759c6f85366aaa53d

with https://reqbin.com and I don't see CORS unfortunately.

Server: nginx/1.14.1
Date: Sun, 23 Feb 2020 17:00:17 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Set-Cookie: PHPSESSID=a666c631f8bf297ae47dc4268ced67cc; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Content-Encoding: gzip

because of this issue, I can't use my API in js app's: https://svelte.dev/repl/e25e8814cc064868b67dad11c90ed029?version=3.19.0

tuupola commented 4 years ago

Quickly testing the middleware seems to be working. Atleast access-control-allow-origin header is added.

$ curl  "https://flextype.org/api/delivery/entries?id=en&token=1a48b9de0494240759c6f85366aaa53d" \
  --include \
  --header "Origin: http://www.example.com"

HTTP/2 404 
server: nginx/1.14.1
date: Mon, 24 Feb 2020 04:11:13 GMT
content-type: text/html; charset=UTF-8
content-length: 6872
vary: Accept-Encoding
set-cookie: PHPSESSID=73466bc391f2f556334b53273b022e68; path=/
expires: Thu, 19 Nov 1981 08:52:00 GMT
cache-control: no-store, no-cache, must-revalidate
pragma: no-cache
access-control-allow-origin: http://www.example.com
vary: Origin

So my guess is JavaScript is not doing an actual CORS request. The CORS headers are only added to responses which require them, not all responses. This flowchart explains in better.

Hower the preflight route seems not to be working.

$ curl "https://flextype.org/api/delivery/entries?id=en&token=1a48b9de0494240759c6f85366aaa53d" \
  --include \
  --request OPTIONS  \
  --header "Origin: http://www.example.com" \
  --header "Access-Control-Request-Method: PUT"  \
   --header "Access-Control-Request-Headers: Authorization, If-Match"

HTTP/2 401 
server: nginx/1.14.1
date: Mon, 24 Feb 2020 04:23:11 GMT
content-length: 0
set-cookie: PHPSESSID=f3cc9a8331a11bf2143342ae02dc043f; path=/
expires: Thu, 19 Nov 1981 08:52:00 GMT
cache-control: no-store, no-cache, must-revalidate
pragma: no-cache

I am pretty sure this is because the request does not reach PHP. IIRC Nginx default config catches OPTIONS requests and handles them by itself.