-1

I have a situation that goes like this : I have a php project that I made from scratch serving as an API endpoint to a client web app created with React. For now they are both locally, php running on localhost:8000 and react on localhost:3000. The issue appears when I try to make token protected request using axios. The php generated session is lost after login.

I've tried to add withCredentials:true client side and also enable header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); in the server side as many of the accpeted answers here mentioned but did not have no luck.

PHP headers :

header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With, Set-Cookie, Cookie, Bearer');

Axios request:

return axios({
    method: 'GET',
    url: LOAD_NOTES_ENDPOINT,
    headers: {'Authorization': token, 'Access-Control-Allow-Origin': '*',}
})
.then(response => {
    console.log(response.data);
    return response;
})
.catch(
    (err) => {
        return err.response;
    }
);

Currently I'm able to send generate token on login and send it back when trying to access protected route and this works fine if I make the request on Postman and this confirmed that this is strictly a CORS issue. I've struggled for 2 days now to find a solution and opened every possible link on the web regarding this issue but all of them are are proposing things I've already tried and didn't work. I could find a workaround but that would leave the server open to CSRF attacks and that is something that I have to prevent.

I'm I missing something here? Did anyone else find a solution about this?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Maro Paro
  • 111
  • 1
  • 2
  • 12
  • What is the content of $_SERVER['HTTP_ORIGIN']? Did you try using "Access-Control-Allow-Origin: *" in PHP? – Sebastian May 03 '19 at 20:40
  • @Sebastian `http://localhost:3000` , and yes I tried with allowing all origins. – Maro Paro May 03 '19 at 20:41
  • *“confirmed that this is strictly a CORS issue”* How exactly did you confirm that? When things don’t work the way you expect, what is the exact error message the browser is logging in the devtools console? – sideshowbarker May 04 '19 at 02:50

1 Answers1

0

Well, I don't know what's going wrong there. However I got it running with this little setup:

file 55976696.php

header('Access-Control-Allow-Origin: http://localhost:3000');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With, Set-Cookie, Cookie, Bearer');

echo json_encode('php successs');

php -S localhost:8000 55976696.php

file 55976696.js

var express = require('express');
const app = express()

app.get('/', (req, res) => res.sendFile('55976696.html', {root: __dirname}))

app.listen(3000, () => console.log(`Example app listening on port 3000!`))

file 55976696.html

<html>
<head>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
function test() {
    axios.get('http://localhost:8000', {
        withCredentials: false,
    }).then(res => { 
        console.log('SUCCESS', res);
    }).catch(error => {
        console.log('erro', error);
    })
   }; 
</script>
</head>
<body>
test
<div onClick="test()">go</div>
</body>
</html>

node 55976696.js

There is just a little change to your axios.get call and I made sure that the PHP header is what I want ...

Sebastian
  • 416
  • 1
  • 6
  • 19
  • Were you able to access the same session ? Cause this is where I'm failing. I can't seem to reach the session that is generated in the login route at this route that I'm trying to reach now. – Maro Paro May 03 '19 at 21:34
  • I did not try that. I think that you have to make sure that the php session id is delivered correctly. Do you transfer it via query? However if you develop an api, I suggest that you do not use php sessions at all, you should prefer a token solution and store the session in the client – Sebastian May 03 '19 at 21:37
  • I would also use a sessionless token like JWT or something similar, but that was my challenge. To be able to do the backend without using any libraries at all. I've been using frameworks for a long time and I decided to learn more about PHP by accepting such a challenge. Anyways, thanks for the help and your time. Much appreciated. – Maro Paro May 03 '19 at 21:43
  • Take a lookt here: https://stackoverflow.com/questions/1612177/are-http-cookies-port-specific – Sebastian May 03 '19 at 21:50