Authentication and Authorization
Separate identity verification from permission checks and return the correct HTTP responses.
Lesson content
🎯 Goal By the end of this lesson, you'll understand: What is Authentication? What is Authorization? Difference between Authentication and Authorization How Login works JWT Authentication Flow Role-Based Authorization Express.js examples Real-world examples Interview questions What is Authentication? Authentication is the process of verifying the identity of a user . It answers the question: Who are you? Examples: Login with Email & Password Login with Google Login with OTP Login with Fingerprint Simple Definition: Authentication verifies that the user is who they claim to be. What is Authorization? Authorization is the process of checking what an authenticated user is allowed to do . It answers the question: What are you allowed to access? Examples: Admin can delete users. Customer can place orders. Employee can view reports. Simple Definition: Authorization determines the permissions of an authenticated user. Why Do We Need Authentication? Authentication helps to: Verify users Protect personal data Prevent unauthorized access Secure applications Why Do We Need Authorization? Authorization helps to: Control access to resources Restrict sensitive operations Implement user roles Improve application security Real-Life Example 🏢 Imagine entering a company. Employee │ ▼ Security Guard (Authentication) │ ▼ Identity Verified │ ▼ Department Access Check (Authorization) │ ▼ Office Access Authentication vs Authorization Authentication Authorization Verifies identity Checks permissions Who are you? What can you do? Happens first Happens after authentication Example: Login Example: Access Admin Panel Authentication Flow User Login │ ▼ Enter Email & Password │ ▼ Server Verifies Credentials │ ▼ Generate JWT │ ▼ Send JWT to Client │ ▼ User Logged In Authorization Flow User Sends JWT │ ▼ Server Verifies JWT │ ▼ User Role Found │ ▼ Permission Checked │ ▼ Access Granted / Denied Express Login Example const jwt = require ( "jsonwebtoken" ); app . post( "/login" , ( req , res ) => { // Normally, verify the user from the database const user = { id: 1 , name: "Ajay" , role: "admin" }; const token = jwt . sign( user , process . env . JWT_SECRET, { expiresIn: "1h" } ); res . json({ token }); }); Authentication Middleware const jwt = require ( "jsonwebtoken" ); function authenticate ( req , res , next ) { const authHeader = req . headers . authorization; if ( ! authHeader ) { return res . status( 401 ) . json({ message: "Token Missing" }); } const token = authHeader . split( " " )[ 1 ]; try { const user = jwt . verify( token , process . env . JWT_SECRET ); req . user = user ; next (); } catch { return res . status( 401 ) . json({ message: "Invalid Token" }); } } Authorization Middleware function authorize (... roles ) { return ( req , res , next ) => { if ( ! roles . includes( req . user . role)) { return res . status( 403 ) . json({ message: "Access Denied" }); } next (); }; } Protected Routes app . get( "/admin" , authenticate , authorize ( "admin" ), ( req , res ) => { res . send( "Welcome Admin" ); } ); Multiple Roles app . get( "/dashboard" , authenticate , authorize ( "admin" , "manager" ), ( req , res ) => { res . send( "Dashboard" ); } ); Request Flow Client │ ▼ Login │ ▼ JWT Generated │ ▼ Client Sends JWT │ ▼ Authentication Middleware │ ▼ Authorization Middleware │ ▼ Route Handler │ ▼ Response Role-Based Access Control (RBAC) Role View Products Create Product Delete Product Manage Users Admin ✅ ✅ ✅ ✅ Manager ✅ ✅ ❌ ❌ Customer ✅ ❌ ❌ ❌ Authentication Methods Method Description Username & Password Most common login method OTP One-Time Password OAuth Login with Google, GitHub, Facebook JWT Token-based authentication Session Server-side authentication Biometric Fingerprint or Face ID Common HTTP Status Codes Code Meaning 200 Success 201 Resource Created 400 Bad Request 401 Authentication failed or missing 403 Authenticated but not authorized 404 Resource not found 500 Internal server error Real-Life Example 🛒 Shopping Website Customer Login │ ▼ Authentication │ ▼ Customer Role │ ▼ View Products ✅ Delete Product ❌ Checkout ✅ Interview Question What is Authentication? Answer Authentication is the process of verifying a user's identity before allowing access to the application. What is Authorization? Answer Authorization determines what resources or actions an authenticated user is allowed to access. Which comes first: Authentication or Authorization? Answer Authentication ↓ Authorization Which HTTP status code is returned when authentication fails? Answer 401 Unauthorized Which HTTP status code is returned when the user lacks permission? Answer 403 Forbidden Best Practices ✅ Always authenticate users before checking permissions. ✅ Store JWT secrets in environment variables. ✅ Hash passwords using bcrypt before storing them. ✅ Use HTTPS in production. ✅ Keep JWT expiration times short. ✅ Implement Role-Based Access Control (RBAC). ✅ Validate user input before authentication. ❌ Never store plain-text passwords. ❌ Never hardcode secrets in your source code. ❌ Don't trust user roles sent directly from the client; verify them from a trusted source (such as the verified JWT claims or your database). Key Points ✅ Authentication verifies who the user is . ✅ Authorization determines what the user can do . ✅ Authentication always happens before authorization. ✅ JWT is commonly used for stateless authentication. ✅ RBAC controls access based on user roles. ✅ 401 indicates an authentication problem, while 403 indicates insufficient permissions. 🧠 Easy Formula User Login │ ▼ Authentication (Verify Identity) │ ▼ JWT Generated │ ▼ Client Sends JWT │ ▼ Authorization (Check Permission) │ ▼ Access Granted Authentication = Who are you? Authorization = What can you do? 401 → Not Logged In / Invalid Token 403 → No Permission Remember: 🔐 Authentication = Verify Identity 🛡️ Authorization = Verify Permissions 👤 Authentication comes first 🎭 Authorization checks the user's role or permissions 🚀 Most Express APIs use JWT + Authentication Middleware + Authorization Middleware for secure access