Giriş Oturumları
Coddy'nin Node.js Journey'sinin Kimlik Doğrulama ve Güvenlik bölümünün bir parçası. Ders 5 / 17.
Giriş isteği 200 yanıtı verir, ancak sonraki istekte kimin giriş yaptığı unutulmuştur. Bir oturum bunu hatırlar. Giriş sırasında sunucu, kimsenin tahmin edemeyeceği bir kimlik oluşturur, hangi kullanıcıya ait olduğunu saklar ve bunu çerez olarak gönderir. Sonraki her istek bu kimliği geri getirir ve sunucu kimliği arar.
Kimlik rastgele olmalıdır. Kullanıcı adını içeren bir çerez, herkesin Cookie: sid=ada yazıp Ada olmasına olanak tanır. randomBytes(24) 192 rastgele bit sağlar. Sayfadaki betiklerin çerezi okuyamaması için çerezi httpOnly olarak ayarlayın.
const cartId = randomBytes(24).toString('base64url');
await carts.insertOne({ _id: cartId, items: [] });
res.cookie('cart', cartId, { httpOnly: true });
// sonraki bir istekte
const cart = await carts.findOne({ _id: parseCookies(req.get('cookie')).cart });Görev
KolayPOST /login,{ _id: sid, userId }değerinisessionsiçinde saklar verandomBytes(24).toString('base64url')kullanarakhttpOnlyolansidçerezini ayarlar.GET /me, bu oturum için{ username }yanıtını verir; oturum yoksa 401{ "error": "Log in first" }yanıtını verir.
Kayıt ol, oturum aç, GET /me isteğini gönder, ardından Veriler bölümüne bak.
Kendin dene
import express from 'express';
import { parseCookies } from './cookies.js';
import { notes, 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 });
});
// Bu tarayıcının GET /visit isteğini kaç kez gönderdiğini sayar.
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 });
});
// Notlar. Şimdilik herkes bunları okuyabilir ve yazabilir.
app.get('/notes', async (req, res) => {
res.json(await notes.find().toArray());
});
app.post('/notes', async (req, res) => {
const note = { 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');
});
Kimlik Doğrulama ve Güvenlik bölümündeki tüm dersler
2Oturumlar ve Çerezler
Çerezlerle HatırlamaGiriş Oturumları