安全标头
本课属于 Coddy Node.js 学习旅程的“身份验证与安全”单元。第 20 课,共 24 课。
浏览器默认会猜测并共享信息:它们可能会把文本响应当作脚本,运行来自任何位置的脚本,并且在较旧的浏览器中,将完整的页面地址发送给其他网站。添加几个响应头就能关闭这些行为:
X-Content-Type-Options: nosniff:信任Content-Type,绝不猜测。Referrer-Policy: no-referrer:不要告诉其他网站是哪个页面链接到它们。Content-Security-Policy: default-src 'self':只从此网站加载脚本、样式和图片。
Express 还会添加 X-Powered-By: Express,这会告诉攻击者可以尝试什么。app.disable('x-powered-by') 会将其移除。一个中间件可以为每个响应设置响应头。下面这段代码会设置另外两个响应头:Strict-Transport-Security 会告知浏览器在一年内只能使用 HTTPS,而 Permissions-Policy 会关闭摄像头和麦克风。
app.use((req, res, next) => {
res.set('Strict-Transport-Security', 'max-age=31536000');
res.set('Permissions-Policy', 'camera=(), microphone=()');
next();
});挑战
简单浏览器会进行一些猜测,攻击者可能会利用这些猜测。为每个响应发送三个标头,关闭这些猜测,并停止告知所有人你的服务器运行着哪个框架。
- 在
server.js中,在所有路由之前添加一个中间件。它会在每个响应中设置这三个标头,包括状态码为 401 的错误响应:X-Content-Type-Options: nosniffReferrer-Policy: no-referrerContent-Security-Policy: default-src 'self'。只有GET /页面需要这个标头,但在每个响应中都设置它也没问题。
- Express 会在每个响应中添加
X-Powered-By: Express。创建应用后立即关闭这个功能。
试试看:按“运行”。在未登录的情况下发送 GET /notes:状态码为 401。它的 Headers 选项卡会显示 X-Content-Type-Options: nosniff 和 Referrer-Policy: no-referrer,并且不会显示 X-Powered-By。发送 POST /signup,然后发送 POST /login,两次都使用 {"username": "ada", "password": "correct horse"}。然后发送 GET /:你会看到页面,其中包含相同的标头,以及 Content-Security-Policy: default-src 'self'。
亲手试试
import express from 'express';
import { ObjectId } from 'mongodb';
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());
// 唯一的管理员账号。密码来自环境变量。
await users.insertOne({ username: 'admin', role: 'admin', passwordHash: await hashPassword(process.env.ADMIN_PASSWORD) });
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, role: 'member', 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,
sameSite: 'lax',
secure: true,
maxAge: 24 * 60 * 60 * 1000,
});
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, role: user.role };
next();
}
// 如果已登录用户没有这个角色,就返回 403。
function requireRole(role) {
return (req, res, next) => {
if (req.user.role !== role) {
return res.status(403).json({ error: 'Not allowed' });
}
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();
});
// 以页面形式显示你的笔记。
app.get('/', requireUser, async (req, res) => {
const list = await notes.find({ owner: req.user.id }).toArray();
const items = list.map((note) => `<li>${note.text}</li>`).join('');
res.send(`<!doctype html><title>Vault</title><h1>${req.user.username}'s notes</h1><ul>${items}</ul>`);
});
// 笔记:每个用户只能读写自己的笔记。
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.get('/notes/:id', requireUser, async (req, res) => {
if (!ObjectId.isValid(req.params.id)) {
return res.status(404).json({ error: 'Note not found' });
}
const note = await notes.findOne({ _id: new ObjectId(req.params.id), owner: req.user.id });
if (!note) {
return res.status(404).json({ error: 'Note not found' });
}
res.json(note);
});
app.delete('/notes/:id', requireUser, async (req, res) => {
if (!ObjectId.isValid(req.params.id)) {
return res.status(404).json({ error: 'Note not found' });
}
const { deletedCount } = await notes.deleteOne({ _id: new ObjectId(req.params.id), owner: req.user.id });
if (!deletedCount) {
return res.status(404).json({ error: 'Note not found' });
}
res.status(204).end();
});
// 供管理员查看:账号总数。
app.get('/admin', requireUser, requireRole('admin'), async (req, res) => {
res.json({ users: await users.countDocuments() });
});
app.listen(3000, () => {
console.log('Vault is running on port 3000');
});
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
身份验证与安全中的所有课
自己练习: Express 在线编辑器