Set-Cookie from Remote API not working

笑着哭i 提交于 2020-03-04 08:36:07

问题


I'm currently on project that needs to use an httpOnly cookie. The project requires a direct call to the API.

Let's say it's xxx.com/vx/auth/login that authenticates user login attempt. That endpoint will give response and also set-cookie to the client. Something like this:

Set-Cookie:token=eyJ0b2tlbiI6ImV5SmhiR2NpT2lKSVV6STFOaUlzSW5SNWNDSTZJa3BYVkNKOS5leUoxYVdRaU9pSXhNREEwT0RJd05DSXNJbDlwWkNaNkluWXhYM1Z6WlhKekx6RXdNRFE0TWpBMElpd2libUZ0WlNJNklrRm5kVzVuSUZOMWNubGhJRUpoYm1kellTSXNJbVZ0WVdsc0lqb2ljR0ZwYm1GdVpHVnpkR2x1WldSQWVXRm9iMjh1WTI5ddlpd2liR1YyWld3aU9qQXNJbWxoZENJNk1UUTNOek0zTVRnMk55d2laWGh3SWpveE5EYzNOVFEwTmpZc2ZRLmtUN0IzNW9YYjQ2RmU3WWFLYkd4MXhoYkdGUWJ1TFg1U053N3FWSjNfa2siffQ==; expires=Thu, 27 Oct 2016 05:04:27 GMT; path=/; HttpOnly

But when I look at the devtools, the cookie is not set. Even after I refresh several times.

What do I miss here? Do I need to create a proxy to handle this? * I used to use proxy and it works well


回答1:


I finally managed to solve this problem by coordinating with the backend engineer guy:

  1. Remove wildcard from Access-Control-Allow-Origin and use specific domain origin instead. If not,
  2. Set Access-Control-Allow-Credentials: true

And in the request, I set withCredentials to true.

NOTE: If you set withCredentials to true, you have to set Access-Control-Allow-Credentials to true also. Plus, this won't work if you still use wildcard in your Access-Control-Allow-Origin.

Further reading about "Request With Credentials"




回答2:


In my case, i was using same domain (no-cors).

i figured out : fetch won’t send cookies, unless you set the credentials init option:

fetch(url, {
    method: 'POST',
    credentials: 'same-origin',
    headers: {...},
    ...
  });


来源:https://stackoverflow.com/questions/40231813/set-cookie-from-remote-api-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!