Authentication checks who you are. Authorization checks what you can do. They are different steps to keep apps safe.
Why authorization differs from authentication in Express
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Express
app.use(authenticate); app.use(authorize);
Authentication usually happens before authorization.
Middleware functions in Express help separate these concerns clearly.
Examples
Express
function authenticate(req, res, next) {
// Check user identity
if (req.headers.authorization === 'valid-token') {
req.user = { id: 1, role: 'admin' };
next();
} else {
res.status(401).send('Not authenticated');
}
}Express
function authorize(req, res, next) {
// Check user permission
if (req.user.role === 'admin') {
next();
} else {
res.status(403).send('Not authorized');
}
}Sample Program
This example shows how Express middleware first checks if the user is authenticated, then if they are authorized to access the admin page.
Express
import express from 'express'; const app = express(); function authenticate(req, res, next) { if (req.headers.authorization === 'valid-token') { req.user = { id: 1, role: 'admin' }; next(); } else { res.status(401).send('Not authenticated'); } } function authorize(req, res, next) { if (req.user.role === 'admin') { next(); } else { res.status(403).send('Not authorized'); } } app.use(authenticate); app.get('/admin', authorize, (req, res) => { res.send('Welcome Admin'); }); // Simulate a request with valid token const req = { headers: { authorization: 'valid-token' } }; const res = { status(code) { this.statusCode = code; return this; }, send(message) { this.message = message; } }; let nextCalled = false; function next() { nextCalled = true; } // Run authenticate authenticate(req, res, () => { // Run authorize authorize(req, res, () => { res.send('Welcome Admin'); }); }); console.log(res.message || res.statusCode);
Important Notes
Authentication confirms identity; authorization controls access.
Always authenticate before authorizing in your app flow.
Use clear error codes: 401 for authentication failure, 403 for authorization failure.
Summary
Authentication means checking who the user is.
Authorization means checking what the user can do.
Both are important for app security but serve different purposes.
Practice
1. In Express apps, what is the main difference between
authentication and authorization?easy
Solution
Step 1: Understand authentication purpose
Authentication confirms the user's identity, like logging in.Step 2: Understand authorization purpose
Authorization decides what resources or actions the authenticated user can access.Final Answer:
Authentication verifies who the user is; authorization checks what they can access. -> Option BQuick Check:
Authentication = identity, Authorization = permissions [OK]
Hint: Authentication = who, Authorization = what they can do [OK]
Common Mistakes:
- Confusing authentication with authorization
- Thinking both check the same thing
- Assuming authorization happens before authentication
2. Which Express middleware is typically used for
authentication?easy
Solution
Step 1: Identify authentication middleware
Passport.js is a popular Express middleware for handling authentication.Step 2: Check other options
express.static serves files, express.json parses JSON, cors handles cross-origin requests, none handle authentication.Final Answer:
passport.authenticate() -> Option AQuick Check:
passport.authenticate() = authentication middleware [OK]
Hint: Passport is for authentication in Express [OK]
Common Mistakes:
- Choosing express.static for authentication
- Confusing cors with authentication
- Not knowing passport middleware
3. Consider this Express route snippet:
What status code will be sent if a logged-in user is not an admin?
app.get('/dashboard', (req, res) => {
if (!req.user) {
return res.status(401).send('Not authenticated');
}
if (!req.user.isAdmin) {
return res.status(403).send('Not authorized');
}
res.send('Welcome Admin');
});What status code will be sent if a logged-in user is not an admin?
medium
Solution
Step 1: Check authentication condition
The code checks ifreq.userexists; if not, sends 401 (unauthenticated).Step 2: Check authorization condition
If user exists butisAdminis false, sends 403 (forbidden, unauthorized).Final Answer:
403 -> Option CQuick Check:
Authenticated but not authorized = 403 [OK]
Hint: 401 = no login, 403 = no permission [OK]
Common Mistakes:
- Mixing 401 and 403 status codes
- Assuming 200 is sent without admin rights
- Ignoring the authorization check
4. This Express middleware aims to protect routes:
What is the bug here?
function checkAdmin(req, res, next) {
if (!req.user.isAdmin) {
res.status(401).send('Unauthorized');
}
next();
}What is the bug here?
medium
Solution
Step 1: Analyze req.user usage
The code accessesreq.user.isAdminwithout checking ifreq.userexists, risking a runtime error.Step 2: Check other issues
While 403 is better for authorization failure, the main bug is possible crash from undefinedreq.user.Final Answer:
req.user might be undefined causing an error -> Option AQuick Check:
Always check req.user exists before properties [OK]
Hint: Check req.user exists before isAdmin [OK]
Common Mistakes:
- Ignoring possible undefined req.user
- Confusing 401 and 403 status codes
- Not returning after sending response
5. You want to protect an Express route so only authenticated users with role 'editor' or 'admin' can access it. Which middleware logic correctly implements this authorization check?
hard
Solution
Step 1: Check authentication and authorization together
The middleware must first confirmreq.userexists (authenticated), then check if role is 'editor' or 'admin'.Step 2: Analyze each option
if (!req.user || (req.user.role !== 'editor' && req.user.role !== 'admin')) { res.status(403).send('Forbidden'); } else { next(); } correctly denies access if no user or role not allowed, sending 403 Forbidden. Others have logic errors or wrong status codes.Final Answer:
if (!req.user || (req.user.role !== 'editor' && req.user.role !== 'admin')) { res.status(403).send('Forbidden'); } else { next(); } -> Option DQuick Check:
Check user exists AND role allowed for authorization [OK]
Hint: Check user exists AND role matches before next() [OK]
Common Mistakes:
- Not checking if user is authenticated first
- Using wrong status codes (401 vs 403)
- Incorrect logical operators in role check
