I have a backend hosted in https://api.mydomain.abc
, and I'm developing a frontend with vue/quasar CLI that uses webpack server.
When the frontend is running in developement mode it's hosted by webpack web server, and the urls in the frontend code have /api/index.php
format. Then the webpack server is configured to proxy them to the real backend url:
devServer: {
...,
proxy: {
// proxy all requests starting with /api to avoid cors problems.
'/api': {
target: 'https://api.mydomain.abc',
changeOrigin: true,
pathRewrite: {
'^/api': '' //remove /api from the final url
}
}
}
},
When running in production mode the fronted is hosted by an NGINX server at https://www.mydomain.abc
and the urls in the front end now are directly like https://api.mydomain.abc
.
From now on, both request types (development and production) are the same. https://api.mydomain.abc
requests are listened by the same NGINX server but now working as reverse proxy, that redirects them to an apache server with PHP mod. Here there is a very simple plain PHP script without any external framework or library, that simply manages login and return some dynamic values from DB if user is correctly logged.
The point is that in developement environment everything works flawlessly, but with the production environment all the login protected requests fails because $_SESSION array is empty!!
I'm completely clueless what could cause these kind of error, since the backend it's the same for both environments.
Further info:
- CORS headers are set in apache server to allow requests from www.mydomain.abc (and also mydomain.abc), and there aren't any CORS errors.
- Both environments access the backend with
https
protocol - My PHP script runs
session_start()
unconditionally at the begining of the script
I have tried this answer but no changes have been observed.
What could cause this difference between both environments? They are practically the same apart from the webpack server.
CodePudding user response:
I will answer it myself. The problem was that during development the browser was in localhost url, doing requests to a localhost server (the webpack server, than then was proxying it to the real api production server, but browser was unaware of that). It was a same-origin
enviroment for the browser, so fetch
API was sending the credentials (phpsessioncookie) to the server as it's the default behaviour in same-origin
environments.
In production environment, the webpack server wasn't into the mix, and the browser was in (www.)mydomain.com
doing requests to api.mydomain.com
. The problem here is that even if (www.)mydomain.com
was set as an allowed origin in the API web server, for the browser it was a cross-origin
environment, which implies that the fetch
API doesn't send the credentials by default. credentials:include
overrides the default value and sends them.
Also the header Access-Control-Allow-Credentials: "true"
is needed in the server side if it wasn't present.