0

I'm using node/express.js with cookie-session's in my application and am trying to understand the proper way create a unique ID for each session.

Currently, when a user logs in a cookie is stored in their browser with a value, for example: session: ABC123. If the user logs out, the cookie is deleted. When the user logs back in, the same cookie and value are stored in the browser session: ABC123.

Ideally, I would like to randomize the session value so I can count the number of unique sessions this user has created. I'm wondering if there is a way to randomize the cookie-session value on every login -- or, should I be creating a separate cookie that stores a random value for this purpose?

Thanks!

4

1 回答 1

2

生成唯一标识符?这听起来像是通用唯一标识符的工作——UUID!有一个可爱的 Node.js 小包uuid,可以为您处理它们背后的逻辑。以下是您可以使用它在 ExpressJS 应用程序中设置唯一 cookie 的方法:

const express = require('express');
const uuid    = require('uuid/v4');

const app = express();

app.get('/', (req, res) => {
  if (req.cookie.id) {
    return res.end(`Welcome back, ${req.cookie.id}!`);
  }

  const id = uuid();

  res.cookie('id', id, { httpOnly: true });
  res.end(`Welcome, ${id}!`);
});

app.listen(3000);

您的确切用法可能会有所不同,因为您只需要在有人登录时生成一个新的 UUID,但原理是相同的。

PS - 您是否考虑过express-session用于识别应用程序的单个用户的包?

于 2018-11-29T19:29:57.327 回答