System Design
Security asoslari
Authentication vs Authorization
Authentication: Kim siz?
Authorization: Nima qila olasiz?
Authentication: Login with email/password
Authorization: Can you access admin panel? /
Authentication Methods
1. Session-based
// Login
app.post('/login', (req, res) => {
const user = verifyCredentials(req.body);
req.session.userId = user.id;
res.json({ success: true });
});
// Protected route
app.get('/profile', (req, res) => {
if (!req.session.userId) return res.status(401);
res.json({ profile: ... });
});
2. JWT (Token-based)
// Login
app.post('/login', (req, res) => {
const user = verifyCredentials(req.body);
const token = jwt.sign({ userId: user.id }, SECRET);
res.json({ token });
});
// Protected route
app.get('/profile', (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const decoded = jwt.verify(token, SECRET);
res.json({ profile: ... });
});
3. OAuth 2.0
User → Your App → OAuth Provider (Google)
→ Returns access token
Your App → Use token to access user data
Password Security
const bcrypt = require('bcrypt');
// Hash password
const hashedPassword = await bcrypt.hash(password, 10);
await db.saveUser({ email, password: hashedPassword });
// Verify
const match = await bcrypt.compare(inputPassword, storedHash);
Never: Plain text passwords
Always: Hash with salt (bcrypt, argon2)
HTTPS / TLS
HTTP: Client → [plain text] → Server
HTTPS: Client → [encrypted] → Server
Always use HTTPS in production!
Common Vulnerabilities
1. SQL Injection
// Vulnerable
const query = `SELECT * FROM users WHERE email = '${email}'`;
// Input: ' OR '1'='1
// Safe (parameterized)
const query = 'SELECT * FROM users WHERE email = ?';
db.query(query, [email]);
2. XSS (Cross-Site Scripting)
// Vulnerable
res.send(`<div>${userInput}</div>`);
// Input: <script>alert('XSS')</script>
// Safe (escape)
res.send(`<div>${escape(userInput)}</div>`);
3. CSRF (Cross-Site Request Forgery)
// Use CSRF tokens
app.use(csrf());
app.post('/transfer', csrfProtection, (req, res) => {
// Process
});
Best Practices
- Principle of Least Privilege
- Defense in Depth (multiple layers)
- Regular security audits
- Keep dependencies updated
- Rate limiting
- Input validation
Keyingi dars: Disaster Recovery.