Authentication & Authorization
Authentication & Authorization
Phần tiêu đề “Authentication & Authorization”Implement authentication và authorization cho ứng dụng.
JWT (JSON Web Tokens)
Phần tiêu đề “JWT (JSON Web Tokens)”import jwt from "jsonwebtoken";
// Generate tokenconst token = jwt.sign({ userId: 123, email: "phi@example.com" }, process.env.JWT_SECRET, { expiresIn: "7d" });
// Verify tokentry { const decoded = jwt.verify(token, process.env.JWT_SECRET); console.log(decoded.userId); // 123} catch (error) { console.error("Invalid token");}Login Flow
Phần tiêu đề “Login Flow”// Login endpointapp.post("/api/login", async (req, res) => { const { email, password } = req.body;
// Find user const user = await db.users.findUnique({ where: { email } }); if (!user) { return res.status(401).json({ error: "Invalid credentials" }); }
// Verify password const valid = await bcrypt.compare(password, user.passwordHash); if (!valid) { return res.status(401).json({ error: "Invalid credentials" }); }
// Generate token const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: "7d" });
res.json({ token, user: { id: user.id, email: user.email } });});Password Hashing
Phần tiêu đề “Password Hashing”import bcrypt from "bcrypt";
// Hash passwordconst hash = await bcrypt.hash(password, 10);
// Store in databaseawait db.users.create({ data: { email, passwordHash: hash, },});
// Verify passwordconst valid = await bcrypt.compare(inputPassword, storedHash);Protected Routes
Phần tiêu đề “Protected Routes”function authenticate(req, res, next) { const token = req.headers.authorization?.split(" ")[1];
if (!token) { return res.status(401).json({ error: "No token provided" }); }
try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.userId = decoded.userId; next(); } catch (error) { res.status(401).json({ error: "Invalid token" }); }}
// Use middlewareapp.get("/api/profile", authenticate, async (req, res) => { const user = await db.users.findUnique({ where: { id: req.userId } }); res.json(user);});Role-Based Access Control (RBAC)
Phần tiêu đề “Role-Based Access Control (RBAC)”function authorize(...allowedRoles) { return async (req, res, next) => { const user = await db.users.findUnique({ where: { id: req.userId } });
if (!allowedRoles.includes(user.role)) { return res.status(403).json({ error: "Forbidden" }); }
next(); };}
// Admin only routeapp.delete("/api/users/:id", authenticate, authorize("admin"), async (req, res) => { // Delete user});Best Practices
Phần tiêu đề “Best Practices”- Hash passwords - Never store plain text
- HTTPS only - Encrypt data in transit
- Secure tokens - Strong secret, reasonable expiry
- Refresh tokens - Long-lived, revocable
- Rate limiting - Prevent brute force
- Input validation - Sanitize user input