tuupola / slim-jwt-auth

PSR-7 and PSR-15 JWT Authentication Middleware
https://appelsiini.net/projects/slim-jwt-auth
MIT License
827 stars 141 forks source link

CORS blocked with JwtAuth #203

Closed raphmte closed 3 years ago

raphmte commented 3 years ago

Hello, I am putting my API into production and I have the following problem.

When I make a request to an endpoint that is not protected by Jwt it works perfectly, however when I make the request to the endpoint that is protected the browser accuses that there is no Access-Control-Allow-Origin header.

CORS configuration:

$app->add(new Tuupola\Middleware\CorsMiddleware([
    "origin" => ["*"],
    "methods" => ["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
    "headers.allow" => ["Origin", "Content-Type", "Authorization", "Accept", "ignoreLoadingBar", "X-Requested-With", "Access-Control-Allow-Origin"],
    "headers.expose" => [],
    "credentials" => true,
    "cache" => 0,
]));

Jwt config:

$app->add(new Tuupola\Middleware\JwtAuthentication([
    "secret" => getenv("JWT_SECRET_KEY"),
    "attribute" => 'jwt',
    "ignore" => [
        "{$defaultPath}/v1/user/login"
    ]
]));

With this configuration, if I make a call to /v1/user/login it works perfectly, but if I do to any other (since all are protected by Jwt) the browser sends me the CORS error.

Error: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I appreciate if anyone has an idea of how I can solve this.

tuupola commented 3 years ago

Can you do a curl request and paste both request and response with headers here. For example:

$ curl "https://api.example.com/foo" \
    --request PUT \
    --include \
    --header "Origin: https://www.example.com"

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://www.example.com
Access-Control-Allow-Credentials: true
Vary: Origin
Access-Control-Expose-Headers: Etag
raphmte commented 3 years ago

Can you do a curl request and paste both request and response with headers here. For example:

$ curl "https://api.example.com/foo" \
    --request PUT \
    --include \
    --header "Origin: https://www.example.com"

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://www.example.com
Access-Control-Allow-Credentials: true
Vary: Origin
Access-Control-Expose-Headers: Etag

The problem was solved by always using HTTPS in the application and the API.

Thank you in advance for your help. =D