最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set-Cookie from Remote API not working - Stack Overflow

programmeradmin2浏览0评论

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/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

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

Share Improve this question edited Jan 2, 2017 at 3:48 asubanovsky asked Oct 25, 2016 at 5:10 asubanovskyasubanovsky 1,7483 gold badges19 silver badges37 bronze badges 7
  • Browsers sometimes don't show it. Is it sent back with the next response? – Max Koretskyi Commented Oct 25, 2016 at 5:16
  • Yes, it is. As mentioned in the question, one of the response-header is 'set-cookie'. – asubanovsky Commented Oct 25, 2016 at 5:37
  • so what is your question? if it's sent back, it's working – Max Koretskyi Commented Oct 25, 2016 at 5:40
  • In my case, the cookie isn't set at all even though there's a set-cookie header from the response. What do I miss here? – asubanovsky Commented Oct 25, 2016 at 7:39
  • when you send request to server after the request with set-cookie, what's inside cookie: header? – Max Koretskyi Commented Oct 25, 2016 at 7:51
 |  Show 2 more comments

3 Answers 3

Reset to default 23

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"

Currently, I made something like this.

//API REST ROUTE
app.get('/login', function(req, res){ 
    console.log('login route', process.env.NODE_ENV);
    const token = '*/*--=3432432$%^%$'
    
    res.set('Access-Control-Allow-Origin', req.headers.origin); //req.headers.origin
    res.set('Access-Control-Allow-Credentials', 'true');
    // access-control-expose-headers allows JS in the browser to see headers other than the default 7
    res.set(
        'Access-Control-Expose-Headers',
        'date, etag, access-control-allow-origin, access-control-allow-credentials'
    );
    
    res
        .cookie('rest-auth-cookie', token, {
            httpOnly: true,
            // secure: process.env.NODE_ENV !== 'development',
            sameSite: 'strict',
            // maxAge: 100,
            path: '/'
          })
        .status(200)
        .json({message: 'success'})
}); 

and

// Client Page
const loginAction = function() {
        let req = new Request(REMOTE_LOGIN_URL, {
          mode: 'cors', //just a safe-guard indicating our intentions of what to allow
          credentials: 'include', //when will the cookies and authorization header be sent
        });
    const apiRestLogin = function() {
      fetch(req)
        .then(resp => {
          console.log('resp', resp);
          
          return resp.json()
        }).then(resp => {
            console.log(resp)
            // router.push('/');
        });
    }

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: {...},
    ...
  });
发布评论

评论列表(0)

  1. 暂无评论