חתימה על אסימונים
חלק מהיחידה אימות ואבטחה במסלול ה-Node.js של Coddy. שיעור 10 מתוך 17.
לאסימון יש ערך רק אם אף אחד אחר לא יכול ליצור אחד. jose חותמת עליו באמצעות HS256: HMAC של הכותרת והמטען, כשהמפתח הוא סוד שרק השרת מכיר.
הסוד מגיע ממשתנה סביבה, process.env.JWT_SECRET, ולא מהקוד: הקוד משותף, מועתק ונשמר במאגר. השיעור הזה מגדיר עבורך את JWT_SECRET. jose צריכה אותו כבתים.
const key = new TextEncoder().encode(process.env.INVITE_SECRET);
const invite = await new SignJWT({ room: 'design' })
.setProtectedHeader({ alg: 'HS256' })
.setSubject(guestId)
.setIssuedAt()
.setExpirationTime('2d')
.sign(key);setSubject מקבלת טקסט, ו-setExpirationTime מקבלת משך זמן כמו '30m' או '2d'.
אתגר
קלPOST /tokenעם{ username, password }מחזיר{ token }: HS256, חתום באמצעותJWT_SECRET, עם הטענהusername, נושא שהוא מזהה המשתמש כטקסט, ותוקף של שעה.- התחברות שגויה מחזירה 401
{ "error": "Wrong username or password" }.
הירשם, קבל אסימון והדבק אותו ב-GET /inspect?token=.
נסו בעצמכם
import express from 'express';
import { decodeJwt } from 'jose';
import { 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' });
}
res.json({ username: user.username });
});
// מציג את תוכן הטוקן: GET /inspect?token=...
app.get('/inspect', (req, res) => {
try {
res.json(decodeJwt(String(req.query.token ?? '')));
} catch {
res.status(400).json({ error: 'Not a JWT' });
}
});
// עמוד הניהול. אין לסמוך על אף טענה לפני שבודקים את החתימה שלה.
app.get('/admin', (req, res) => {
res.status(403).json({ error: 'Admins only' });
});
app.listen(3000, () => {
console.log('Vault is running on port 3000');
});