繁体   English   中英

为什么不发送Set-Cookie标头? -使用Restify

[英]Why is the Set-Cookie header not being sent? — using Restify

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

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

更多信息:

标头上的回应

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,上面写着“发回请求!” 当响应被发送回服务器并包含正确的内容时,即使该语句出现在res.send()之前,它也永远不会出现在控制台中。

经过我的同事的检查和帮助之后,问题在于res.cookie()未定义。 我以某种方式引起了我的restify.js ,我们正在使用的服务器restify.jsexpress.js的超集。 它不是! 我应该使用的功能是res.setCookie()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM