Menu
CoddyTech

Cookie 标志

本课属于 Coddy Node.js 学习旅程的“身份验证与安全”单元。第 13 课,共 24 课。

没有安全标记的 cookie 会通过普通 HTTP 传输,会随其他网站触发的请求一起发送,并且会一直存在,直到浏览器关闭。通过 res.cookie 设置四个选项可以加强保护:

  • httpOnly:页面中的脚本无法读取它。
  • sameSite:'lax' 会阻止它随发送到其他网站的请求一起发送,但用户点击链接时除外;'strict' 则连这种情况也会阻止。
  • secure:只通过 HTTPS 发送,绝不会通过普通 HTTP 发送,以免网络上的其他人读取它。
  • maxAge:它的存活时长,单位为毫秒。
res.cookie('cart', cartId, {
    httpOnly: true,
    sameSite: 'strict',
    secure: true,
    maxAge: 30 * 60 * 1000, // 30 分钟
});
challenge icon

挑战

简单

收紧 sid Cookie 的设置,让浏览器只在适当的情况下发送它,并在一天后忘记它。

  1. 在 server.js 的 POST /login 中,为 sid Cookie 设置以下四个选项:
    • httpOnly,这样页面中的脚本就无法读取它。它已经设置了这个选项。
    • 将 sameSite 设为 'lax',这样浏览器就不会在其他网站发起的请求中发送它,除非用户点击链接访问你的网站。
    • secure,这样它只会通过 HTTPS 发送。
    • 将 maxAge 设为一天。maxAge 的单位是毫秒,而响应头显示的时间单位是秒,所以一天会显示为 Max-Age=86400。
  2. 登录仍然必须正常工作:发送 POST /login 后,GET /me 会返回用户。

试试看:点击“运行”。发送 POST /signup,然后发送 POST /login,两次都使用 {"username": "ada", "password": "correct horse"}。打开登录响应的 Headers 选项卡。Set-Cookie 的内容类似于 sid=oqjRxvxmXl_nRwAwOLxgZyI2sYq9hZtN; Max-Age=86400; Path=/; Expires=Sat, 31 Oct 2026 12:00:00 GMT; HttpOnly; Secure; SameSite=Lax。发送 GET /me:{"username": "ada"}。

亲手试试

import express from 'express';
import { randomBytes } from 'node:crypto';
import { parseCookies } from './cookies.js';
import { notes, sessions, users } from './db.js';
import { hashPassword, verifyPassword } from './passwords.js';

const app = express();
app.use(express.json());

app.post('/signup', async (req, res) => {
    const username = String(req.body.username ?? '').trim().toLowerCase();
    const password = String(req.body.password ?? '');
    if (!username || password.length < 8) {
        return res.status(400).json({ error: 'Pick a username and a password of at least 8 characters' });
    }
    if (await users.findOne({ username })) {
        return res.status(409).json({ error: 'That username is taken' });
    }
    await users.insertOne({ username, passwordHash: await hashPassword(password) });
    res.status(201).json({ username });
});

app.post('/login', async (req, res) => {
    const username = String(req.body.username ?? '').trim().toLowerCase();
    const user = await users.findOne({ username });
    if (!user || !(await verifyPassword(String(req.body.password ?? ''), user.passwordHash))) {
        return res.status(401).json({ error: 'Wrong username or password' });
    }
    const sid = randomBytes(24).toString('base64url');
    await sessions.insertOne({ _id: sid, userId: user._id, createdAt: new Date() });
    res.cookie('sid', sid, { httpOnly: true });
    res.json({ username: user.username });
});

// 查找会话 cookie 对应的用户,找不到则返回 401。
async function requireUser(req, res, next) {
    const { sid } = parseCookies(req.get('cookie'));
    const session = sid && (await sessions.findOne({ _id: sid }));
    const user = session && (await users.findOne({ _id: session.userId }));
    if (!user) {
        return res.status(401).json({ error: 'Log in first' });
    }
    req.user = { id: user._id.toHexString(), username: user.username };
    next();
}

app.get('/me', requireUser, (req, res) => {
    res.json({ username: req.user.username });
});

app.post('/logout', async (req, res) => {
    const { sid } = parseCookies(req.get('cookie'));
    if (sid) {
        await sessions.deleteOne({ _id: sid });
    }
    res.clearCookie('sid');
    res.status(204).end();
});

// 统计此浏览器调用 GET /visit 的次数。
app.get('/visit', (req, res) => {
    const cookies = parseCookies(req.get('cookie'));
    const visits = Number(cookies.visits ?? 0) + 1;
    res.cookie('visits', String(visits));
    res.json({ visits });
});

// 笔记:每个用户只能读写自己的笔记。
app.get('/notes', requireUser, async (req, res) => {
    res.json(await notes.find({ owner: req.user.id }).toArray());
});

app.post('/notes', requireUser, async (req, res) => {
    const note = { owner: req.user.id, text: String(req.body.text ?? '') };
    await notes.insertOne(note);
    res.status(201).json(note);
});

app.listen(3000, () => {
    console.log('Vault is running on port 3000');
});
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

身份验证与安全中的所有课

自己练习: Express 在线编辑器