Autentikasi memverifikasi identitas user. JWT (JSON Web Token) adalah cara populer untuk autentikasi API.
Alur autentikasi:
1. User login dengan email + password
2. Server verifikasi → buat JWT token
3. Client simpan token
4. Setiap request, kirim token di header
5. Server verifikasi token → beri akses
JWT structure:
eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.abc123
HEADER . PAYLOAD . SIGNATURE
Login endpoint:
app.post("/login", async (req, res) => {
const { email, password } = req.body;
const user = await findUserByEmail(email);
if (!user || !verifyPassword(password, user.password)) {
return res.status(401).json({ error: "Invalid credentials" });
}
const token = jwt.sign({ userId: user.id }, SECRET, { expiresIn: "7d" });
res.json({ token });
});
Auth middleware:
function authMiddleware(req, res, next) {
const token = req.headers.authorization?.split(" ")[1];
if (!token) return res.status(401).json({ error: "No token" });
try {
const decoded = jwt.verify(token, SECRET);
req.userId = decoded.userId;
next();
} catch {
res.status(401).json({ error: "Invalid token" });
}
}