如何使用节点 cookie-session 创建 cookie

How to create a cookie with node cookie-session

我是运行一个小节点app。我试图让它为每个访问者创建一个名为 'session' 的 cookie,其中包含 - 例如 - 会话 ID。但是我似乎无法让节点通过 cookie-session 创建 cookie。到目前为止我的代码:

const fs = require('fs');
const http = require('http');
const https = require('https');
const privateKey = fs.readFileSync('PATHTOKEY');
const certificate = fs.readFileSync('PATHTOKEY');
const credentials = {key: privateKey, cert: certificate};
const Keygrip = require("keygrip");    

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

const port = APORTNUMBER;
const secureport = APORTNUMBER;
const helmet = require('helmet');    

const options = {
  dotfiles: 'deny',
  etag: true,
  extensions: ['html', 'htm'],
  index: 'index.html',
  lastModified: true,
  maxAge: 0,
  redirect: true,
  setHeaders: function (res, path, stat) {
    res.set('x-timestamp', Date.now())
  }
};    

app.use(express.static('public', options), helmet());    

到目前为止,没有问题。但接下来是中间件 cookie-session。

const session = require('cookie-session');
const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour    

app.use( 
  session({
    name: 'session',
    keys: new Keygrip(["MYSECRET1", "MYSECRET2"]),
    cookie: {
      secure: true,
      httpOnly: true,
      expires: expiryDate
    }
  })
);    

在上面,我已经指定了中间件来使用这些 cookie-session 参数,但是我如何从这里开始真正获取它来创建这个 cookie?

const httpServer = http.createServer(app);
const httpsServer = https.createServer(credentials, app);    

httpServer.listen(port);
httpsServer.listen(secureport);    

console.log("Node server started");

您当前的代码看起来是正确的,同样基于文档 @ http://expressjs.com/en/resources/middleware/cookie-session.html

我建议定义一个 app.get 并使用 postman 或 fidler 等工具测试所有内容。

例如

app.get('/test', function (req, res, next) {
  // Update views
  req.session.views = (req.session.views || 0) + 1

  // Write response
  res.end(req.session.views + ' views')
})

我无法弄清楚如何使用 express-cookie 和 cookie-session。但是,我已经能够使用 cookie-parser 中间件创建 cookie。

依赖性:

const cookieParser = require('cookie-parser');

配置:

const cookieConfig = {
  httpOnly: true,
  secure: true,
  maxAge: 1800,
  signed: true
};

快递:

app.use(cookieParser('MYSECRET'));    

app.use(function (req, res, next) {
  let cookie = req.cookies.cookieName;
  if (cookie === undefined) {
    let randomNumber=LOGICFORRANDOMNUMBER
    res.cookie('COOKIENAME', randomNumber, cookieConfig);
  };
  next();
});

好吧,在我自己尝试之后,我成功地使用了 cookie-session 中间件。耶

我是这样使用中间件的:

app.use(cookieSession({
  name: 'session', // replace this with your own name to suit your needs
  keys: [ 'your-secret-key-goes-here', 'your-secret-key-goes-here' ]
})

关于 keys 选项中的重复值 - 尽管 TypeScript @types lib 声明

,但文档和相关示例始终使用 2 个不同的键

The list of keys to use to sign & verify cookie values. Set cookies are always signed with keys[0], while the other keys are valid for verification, allowing for key rotation.

所以..我只用了一把钥匙..两次...而且它正常工作

请注意,我在注册快速 app 路由之前使用此中间件,以便此中间件在执行路由器之前生效(根据请求)

在我的每条路线中,我都可以使用类似这样的中间件

app.get('/test', (req, res) => {
  req.session.test = { a: 5, b: 7} // yes - JSON payload are valid :)
})

验证 - 确保您的初始请求得到以下 headers

Set-Cookie: session=eyJ0ZXN0Ijp7ImEiOjUsImIiOjd9fQ==; path=/; secure; httponly
Set-Cookie: session.sig=D4VVF4XSbBEWXI4b04ZvybAxppw; path=/; secure; httponly

这只是一个示例,其中 session 是我之前定义的 cookie 的名称。干杯