Q1. What is authentication vs authorization?
Authentication verifies who the user is (login with credentials). Authorization determines what they can access (permissions). In Express, authentication typically happens first (checking username/password), then middleware checks authorization (is user admin?).
Q2. How do you implement basic username/password authentication?
Create a login endpoint that receives credentials. Verify against database (never store plain passwords - use bcrypt to hash). If valid, create a session (express-session) or issue a JWT. Then protect routes by checking session or token.
Q3. How do you store passwords securely?
Never store plain text passwords. Use bcrypt to hash passwords before storing. Example: const hashed = await bcrypt.hash(password, 10). For login, compare: await bcrypt.compare(inputPassword, storedHash). Bcrypt adds salt and is slow, making brute-force difficult.
Q4. What are the common authentication strategies in Express?
Session-based (using express-session with cookies), JWT (JSON Web Tokens) for stateless APIs, OAuth (Google, Facebook login), and Passport.js (middleware that supports many strategies). The choice depends on your application type.
Q5. How do you create a protect middleware for routes?
Write middleware that checks authentication. For sessions: if (!req.session.userId) return res.status(401).send('Unauthorized'); next(). For JWT: verify token from Authorization header, attach user to req, then next(). Apply to protected routes.
