Authentication vs Authorisation
Two Different Questions
Security in web applications revolves around two distinct questions that are often confused:
- Authentication asks: "Who are you?" — It verifies your identity.
- Authorisation asks: "What are you allowed to do?" — It controls your permissions.
These are separate steps. You must be authenticated before you can be authorised, but being authenticated does not automatically grant you access to everything.
Real-world analogy: When you enter an office building, you show your ID card at the reception desk — that is authentication. The receptionist then checks whether you have been granted access to the 4th floor server room — that is authorisation. Your identity and your permissions are separate concerns.
Authentication: Proving Identity
Authentication is the process of verifying that a user is who they claim to be. The most common method is a username (or email) and password combination.
Other authentication factors include:
- Something you know — password, PIN
- Something you have — phone (for SMS OTP (One-Time Password)), hardware key
- Something you are — fingerprint, face ID
Using two or more factors together is called MFA (Multi-Factor Authentication), which dramatically reduces the risk of account compromise.
When a user successfully authenticates, the server needs a way to remember that for future requests. This is done through sessions or tokens.
Cookie-Based Sessions
In cookie-based authentication, after login the server creates a session in its database, generates a session ID, and sends it to the browser as an HTTP cookie.
POST /login
↓
Server creates session: { sessionId: "abc123", userId: 42, expiresAt: ... }
Server sends Set-Cookie: sessionId=abc123
↓
Future requests: browser automatically sends Cookie: sessionId=abc123
Server looks up "abc123" in session store → finds userId 42
Pros: Easy to invalidate (delete the session from the database). Secure with HttpOnly and Secure cookie flags.
Cons: Requires server-side session storage. Harder to scale horizontally across multiple servers.
Token-Based Authentication
In token-based authentication, the server creates a signed token (most commonly a JWT — JSON Web Token) and sends it to the client. The client stores it and sends it with every request in the Authorization header.
POST /login
↓
Server generates signed JWT: eyJhbGci...
Server sends: { "token": "eyJhbGci..." }
↓
Future requests: Authorization: Bearer eyJhbGci...
Server verifies signature → extracts userId from token
Pros: Stateless — the server does not need to store sessions. Scales easily. Works well for APIs consumed by mobile apps.
Cons: Harder to invalidate before expiry. Token must be kept secret (stored securely on the client).
Authorisation: Controlling Permissions
Once a user's identity is confirmed, authorisation determines what they can access or modify. This is typically implemented as roles or permissions.
Role-Based Access Control (RBAC)
RBAC is the most common approach. Every user is assigned a role, and each role has a set of allowed actions.
// User object stored in DB
{
"_id": "64user001",
"name": "Amaka",
"email": "amaka@example.com",
"role": "admin" // or "user", "moderator", "editor"
}
// Middleware that checks role
function requireRole(role) {
return (req, res, next) => {
if (req.user.role !== role) {
return res.status(403).json({ message: 'Forbidden: insufficient permissions' });
}
next();
};
}
// Route only accessible by admins
router.delete('/users/:id', authenticate, requireRole('admin'), deleteUser);
Resource Ownership
Beyond roles, you often need to check whether a user owns the resource they are trying to modify:
// PATCH /posts/:id — only the author can edit their own post
router.patch('/:id', authenticate, async (req, res) => {
const post = await Post.findById(req.params.id);
if (!post) return res.status(404).json({ message: 'Post not found' });
// Authorisation check: is this user the author?
if (post.author.toString() !== req.user._id.toString()) {
return res.status(403).json({ message: 'Forbidden: you did not write this post' });
}
const updated = await Post.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(updated);
});
OAuth Overview
OAuth (Open Authorisation) is a standard that allows a user to grant a third-party application access to their account on another service — without sharing their password.
When you click "Sign in with Google" on a website, OAuth is at work:
- The website redirects you to Google's login page
- You authenticate with Google directly (your password never goes to the website)
- Google asks you to approve what the website can access ("Can this app see your name and email?")
- Google sends a token back to the website confirming your identity
Popular OAuth (Open Authorisation) providers: Google, GitHub, Facebook, Twitter. In Nigeria, some fintech platforms integrate OAuth with their identity verification services.
HTTP Status Codes for Authentication and Authorisation
Getting the right status code matters:
| Situation | Status code |
|---|---|
| User not logged in (not authenticated) | 401 Unauthorized |
| User is logged in but lacks permission | 403 Forbidden |
| Resource not found (regardless of auth) | 404 Not Found |
Do not return 404 when you mean 403 — this hides the real reason for rejection and confuses developers and users.
Practice Exercise
Design the authentication and authorisation layer for a blog API:
- Sketch out the user schema — what fields does a user need for authentication? (hint: email, password hash, role)
- Design three roles:
reader,author, andadmin - List which HTTP endpoints each role can access — for example, only authors and admins can
POST /posts - Write a
requireRole(role)middleware function in Node.js that readsreq.user.roleand returns 403 if the role does not match - Write a resource ownership check for
DELETE /posts/:idthat allows both the post author and admins to delete, but no one else
Try it yourself
Key Takeaways
- Authentication verifies identity ('Who are you?'); authorisation controls permissions ('What can you do?').
- Cookie-based sessions store state on the server; token-based authentication (JWT) is stateless and scales more easily.
- Role-Based Access Control (RBAC) assigns roles to users and checks those roles before allowing access to protected routes.
- Resource ownership checks ensure users can only modify their own data, regardless of their role.
- OAuth (Open Authorisation) lets users grant third-party apps access to their accounts without sharing passwords.
Quick Quiz
1.What is the difference between authentication and authorisation?
2.Which HTTP status code should you return when a logged-in user tries to access a resource they do not have permission to view?
3.What is a key advantage of token-based authentication over cookie-based sessions?
4.What does OAuth (Open Authorisation) allow a user to do?
Ready to go further?
CareerEx gives you structured 12-week training, live classes every Saturday and Sunday, real tutor feedback, and a certificate. Join the next cohort.
Join CareerEx