为什么 Set-Cookie header 没有被发送? -- 使用 Restify

Why is the Set-Cookie header not being sent? -- using Restify

我正在为 Node 应用开发身份验证系统。登录页面向身份验证端点发送 AJAX 请求,然后端点查询我们的用户数据库以确定凭据的有效性。如果端点确定凭据有效,我使用 Express 的 res.cookie() 方法在客户端创建一个 cookie,其中包含以后请求的身份验证信息。

身份验证工作正常,响应正在发送回用户,但是当我查看开发人员工具时,我没有看到 authorization cookie,也没有提到 Set-Cookie header。是什么赋予了?

更多信息:

Headers 回复

restify.CORS.ALLOW_HEADERS.push('Accept-Encoding');
restify.CORS.ALLOW_HEADERS.push('Accept-Language');
restify.CORS.ALLOW_HEADERS.push('authorization');
restify.CORS.ALLOW_HEADERS.push('token');
server.use(restify.CORS({
  origins: ['*'],
  credentials: true,
  headers: ['token']
}));

/* break */

server.opts(/\.*/, function (req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Headers', restify.CORS.ALLOW_HEADERS.join(', '));
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Origin', res.headers.origin);
  res.header('Access-Control-Max-Age', 0);
  res.header('Content-type', 'text/plain charset=UTF-8');
  res.header('Content-length', 0);
  res.send(200);
  next();
});

身份验证的相关部分api

function authHandler(req, res, next) {

  authMan.authenticate(req.params.username,req.params.password).then(function(userdata){
    /*d*/console.log('userData:'+userdata);
    // jwt library for JSON web tokens
    const authorization = jwt.sign(
      {'sub': userdata.username, 'roles': authMan.getGroups(userdata)},
      // global
      authSecret,
      {issuer:'myCompany.com'}
    );

    // Only send the client the user's username and display name
    var strippedData = {};
    strippedData.username = userdata['username'];
    strippedData.displayName = userdata['displayName'];
    // Disable https when not in prod
    var useHttps = true;
    if (process.env[NODE_ENV] === 'dev') {
      useHttps = false;
    }
    res.cookie('authorization', authorization, {
      httpOnly: true, 
      secure: useHttps
    });
    /*d*/console.log('Sent the request back!');
    res.send({
      status: 'OK',
      userdata: strippedData
    });
    next();
  },function(err){
    /*d*/console.log('authHandler error: '+err);
    res.status(401).send({
      status: 'ERROR',
      error: err
    });
    next();
  });
  metrics.log(etc);
  next();
}

你会注意到在上面的代码中,有一个调试 printf 说 "Sent the request back!" 当响应被发送回服务器时,它包含正确的内容,这个语句从未出现在我的控制台中,即使它出现在 res.send().

之前

经过同事的检查和帮助,问题是 res.cookie() 未定义。我不知何故想到 restify.js,我们正在使用的服务器,是 express.js 的超集。它不是!我应该使用的函数是 res.setCookie()