04 Authentication
Security kisi bhi app ka sabse important part hai. Yahan hum seekhenge “Authentication” - yani kaise user ko login karwaya jaye aur secure rakha jaye.
1. Password Store Karna (Hashing) 🔒
Ghalati: Password ko seedha database me save karna. Agar kabhi DB hack hua, to sabke passwords leak ho jayenge!
Sahi Tareeka: “Hashing”. Hum password ko ek algorithm se guzaar kar ajeeb string bana dete hain jise wapas original password me badla nahi ja sakta.
Tool: bcrypt (Sabse popular).
const bcrypt = require('bcrypt');
const password = "mySecretPassword123";const saltRounds = 10;
// Hashing (Signup ke waqt)bcrypt.hash(password, saltRounds, (err, hash) => { // Store 'hash' in your DB (Not the plain password!) console.log(hash); // Output: $2b$10$EixZAYVK1A6iPhLsO2... (Kuch aaisa dikhega)});
// Verification (Login ke waqt)bcrypt.compare("wrongPassword", hash, (err, result) => { console.log(result); // falsef});2. JWT (JSON Web Tokens) 🎟️
Jab user login karta hai, humein yaad rakhna hota hai ki wo kaun hai. Session vs Token (JWT):
- Session (Purana): Server yaad rakhta hai (Memory heavy).
- JWT (Modern): Server user ko ek “Token” (ek signed slip) deta hai. User har agle request pe wo slip dikhata hai.
Kaise Kaam Karta Hai?
- User Login: Username/Password bhejta hai.
- Server Verify: Agar sahi hai, to Server ek JWT banata hai (Secret Key use karke) aur user ko deta hai.
- Future Requests: User header me Token bhejta hai (
Authorization: Bearer <token>). - Server Check: Server token check karta hai aur data de deta hai.
Implementation Example
const jwt = require('jsonwebtoken');const secretKey = "superSecretKey123"; // Ise environment variable me rakhein!
// Token Banana (Login par)const user = { id: 1, name: "Aditya" };const token = jwt.sign(user, secretKey, { expiresIn: '1h' });console.log(token); // User ko ye token dein
// Token Verify Karna (Protected Route par)const receivedToken = "eyJhbGciOiJIUzI1NiIsIn..."; // User se aaya hua token
try { const decoded = jwt.verify(receivedToken, secretKey); console.log("Welcome:", decoded.name);} catch (err) { console.log("Invalid Token! Login again.");}3. Best Practices 🛡️
- HTTPS Use Karein: Bina HTTPS ke Token chori ho sakta hai.
- Environment Variables: Secret Keys ko code me hardcode na karein (
.envfile use karein). - Strong Hashing:
bcryptyaargon2hi use karein. Simple MD5 use na karein.
Summary
- Hashing: Password chupane ke liye (
bcrypt). - JWT: Logged-in user ki pehchan ke liye (
jsonwebtoken). - Flow: Login -> Create Token -> Send Token -> Verify Token.
Next Up: Ab kuch advance cheezein! Streams aur Worker Threads jo Node.js ko super power deti hain. ⚡