
Imagine you're building a web application where users can sign up, log in, and access their dashboards. Some users are regular customers, while others are administrators who can manage users, delete content, and view reports.
But how does your application know who is logging in? And how does it decide which pages or resources that person can access?
This is where authentication and authorization come into play.
These two concepts are essential for building secure web applications, REST APIs, and modern authentication systems. Although developers often use these terms together, they serve different purposes.
In this guide, we'll explore the difference between authentication and authorization, understand how they work, and implement both concepts using Node.js and Express.js.
1. What Is Authentication?
Authentication is the process of verifying the identity of a user, application, or system.
In simple words, authentication answers the question:
"Who are you?"
When you log in to an application using your email and password, the application checks whether your credentials are valid. If they are, it establishes an authenticated session or issues a token that can be used to identify your authenticated session on subsequent requests.
Example of Authentication
Imagine you're logging in to an online shopping application.
You enter:
Email: manjeet@example.com
Password: your_passwordThe application verifies your credentials against the stored account information.
If the credentials are valid, the application establishes your authenticated session.
If the credentials are incorrect, the application rejects the login attempt.
This entire identity-verification process is authentication.
Common Authentication Methods
There are several ways to authenticate users.
1. Username and Password
This is one of the most common authentication methods. Users provide credentials, and the application verifies them.
Passwords should never be stored as plain text. Applications should store password hashes produced by a suitable password-hashing algorithm, such as Argon2id or bcrypt.
2. OTP-Based Authentication
One-Time Password (OTP) authentication verifies a user through a temporary code delivered through a supported channel, such as an authenticator application, email, or SMS.
The application validates the code before allowing the authentication process to continue.
3. Multi-Factor Authentication (MFA)
MFA requires users to verify their identity using two or more distinct authentication factors.
For example, an application might require a password and a code from an authenticator app.
MFA provides additional protection if a password is compromised.
4. Token-Based Authentication
Many REST APIs use tokens to authenticate subsequent requests.
For example, after a successful login, a server may issue a JSON Web Token (JWT). The client then sends the token with requests to protected endpoints.
The server validates the token before processing those requests.
Remember that a JWT is a token format, not an authentication method by itself. Its security depends on how the application issues, validates, stores, and uses it.
5. Social Login
Applications may allow users to sign in through identity providers such as Google or GitHub using protocols such as OpenID Connect or OAuth-based authorization flows.
In this case, the application relies on the identity provider to authenticate the user and securely receives the necessary identity information.
2. What Is Authorization?
Authorization is the process of determining what an authenticated user or system is allowed to access or do.
In simple words, authorization answers the question:
"What are you allowed to do?"
After identifying a user, an application must determine which resources that user can access and which actions they can perform.
For example, a regular user might be allowed to view their own profile, while an administrator might be allowed to manage every user's account.
Authentication establishes identity. Authorization determines permissions.
Example of Authorization
Imagine your application has three types of users:
User: Can view and update their own profile.
Manager: Can view team reports and manage assigned tasks.
Admin: Can manage users, change roles, and access administrative features.
All three users might successfully log in. However, they should not have the same permissions.
If a regular user tries to access an administrative endpoint, the application should deny the request.
For example:
DELETE /api/users/101If deleting users is an administrator-only action, a regular user should not be allowed to perform it—even if they have valid login credentials.
This permission-checking process is authorization.
Common Authorization Models
1. Role-Based Access Control (RBAC)
In RBAC, permissions are associated with roles, and users receive permissions through their assigned roles.
For example:
Admin:
- Create users
- Delete users
- Manage roles
User:
- View own profile
- Update own profileRBAC is commonly used in dashboards, content management systems, and enterprise applications.
2. Permission-Based Authorization
Instead of checking only a user's role, the application checks specific permissions.
For example:
{
"permissions": [
"users:read",
"users:update"
]
}This approach can provide more granular control over what users can do.
3. Attribute-Based Access Control (ABAC)
ABAC makes authorization decisions based on attributes associated with the user, resource, action, or environment.
For example, a manager may access a report only when the report belongs to their department.
This model is useful when authorization rules depend on more than a user's role.
4. Resource Ownership Checks
Some permissions depend on whether the requested resource belongs to the authenticated user.
For example, a user may update their own profile but must not update another user's profile simply by changing an ID in the URL.
This is especially important when developing REST APIs.
3. Authentication vs Authorization: Key Differences
Authentication and authorization work together, but they are not the same.
Feature | Authentication | Authorization |
|---|---|---|
Purpose | Verifies identity | Determines access permissions |
Main question | Who are you? | What can you access? |
When it happens | Usually before protected-resource authorization | After the application has established the relevant identity and context |
Input | Credentials, tokens, or other identity evidence | Identity, roles, permissions, resource ownership, and policies |
Example | Logging in with a password | Checking whether a user can delete a post |
Common mechanisms | Passwords, MFA, sessions, identity tokens | RBAC, ABAC, permission checks, ownership rules |
Failure example | Invalid credentials | Insufficient permissions |
Typical HTTP response |
|
|
One important distinction concerns HTTP status codes.
A 401 Unauthorized response generally means that valid authentication credentials are missing or were not accepted. Despite its name, it is associated with authentication.
A 403 Forbidden response means the server understood the request but refuses to fulfill it. For example, the user may be authenticated but lack the required permission.
An API may also return 404 Not Found when a resource does not exist or when its design intentionally avoids revealing that a restricted resource exists.
4. How Authentication and Authorization Work Together
Let's understand the complete process using a real-world example.
Imagine you're building an admin dashboard using React.js, Node.js, and Express.js.
A user wants to access the dashboard.
Step 1: The User Logs In
The user submits their credentials:
POST /api/auth/login
Content-Type: application/json{
"email": "manjeet@example.com",
"password": "your_password"
}The server verifies the credentials.
If they are valid, it establishes a session or issues an appropriate authentication token.
This is authentication.
Step 2: The User Requests a Protected Resource
The client sends a request to an administrative endpoint:
GET /api/admin/dashboard
Authorization: Bearer <access_token>The server validates the token, including its signature, expiration, and relevant claims.
If the token is invalid or missing, the server rejects the request.
This is the authentication check for the protected endpoint.
Step 3: The Server Checks Permissions
After validating the token, the server checks whether the authenticated user has permission to access the dashboard.
For example:
if (user.role !== "admin") {
return res.status(403).json({
message: "Access denied",
});
}If the user does not have the required permission, access is denied.
This is authorization.
Step 4: The Server Returns the Resource
If the authentication and authorization checks both succeed, the server returns the requested dashboard data.
The complete flow looks like this:
User sends request
|
v
Authenticate the request
|
v
Is the identity valid?
|
+---+---+
| |
No Yes
| |
v v
Reject Check permissions
request |
+---+---+
| |
No Yes
| |
v v
Reject Allow access
and return dataThis separation makes security logic easier to understand, maintain, and test.
5. Implement Authentication and Authorization in Node.js
Let's implement a simplified example using Express.js and JWT.
First, install the required packages:
npm install express jsonwebtokenFor this demonstration, we'll assume that login credentials have already been securely verified and that a trusted user record is available.
In a real application, you must verify the password against its stored hash before issuing a token.
Step 1: Create Authentication Middleware
Authentication middleware checks whether the request contains a valid access token.
const jwt = require("jsonwebtoken");
const authenticateUser = (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return res.status(401).json({
message: "Authentication required",
});
}
const token = authHeader.split(" ")[1];
try {
const decoded = jwt.verify(
token,
process.env.JWT_SECRET
);
req.user = {
id: decoded.sub,
role: decoded.role,
};
next();
} catch (error) {
return res.status(401).json({
message: "Invalid or expired token",
});
}
};This middleware:
Reads the authorization header.
Extracts the bearer token.
Verifies the token.
Attaches trusted identity information to
req.user.Passes control to the next middleware when verification succeeds.
The JWT secret should come from a secure environment configuration and must not be exposed to the client.
The server must also issue tokens only after successful authentication. Do not trust a role or user ID supplied directly by the client.
Step 2: Create Authorization Middleware
Now create middleware that checks whether the authenticated user has the required role.
const authorizeRole = (...allowedRoles) => {
return (req, res, next) => {
if (!req.user) {
return res.status(401).json({
message: "Authentication required",
});
}
if (!allowedRoles.includes(req.user.role)) {
return res.status(403).json({
message: "You do not have permission",
});
}
next();
};
};This middleware receives a list of allowed roles.
If the user's role is included in that list, the request continues. Otherwise, the server returns 403 Forbidden.
Step 3: Protect an Admin Route
Let's use both middlewares in an Express.js route:
const express = require("express");
const app = express();
app.get(
"/api/admin/dashboard",
authenticateUser,
authorizeRole("admin"),
(req, res) => {
res.status(200).json({
message: "Welcome to the admin dashboard",
userId: req.user.id,
});
}
);Notice the order of the middleware:
authenticateUser,
authorizeRole("admin")Authentication runs first so that authorization can use the verified identity.
If a user has a valid token but does not have the admin role, the request is rejected.
Production note: This example demonstrates role-based authorization, not a complete authentication system. Production applications should also implement secure login, appropriate token expiration, secret-key management, account revocation or session invalidation where needed, and resource-level permission checks. For sensitive permissions, consider checking current roles and permissions against the database rather than relying exclusively on potentially outdated token claims.
6. Common Mistakes Developers Should Avoid
Understanding authentication and authorization is important, but implementing them incorrectly can still create security vulnerabilities.
Here are some common mistakes to avoid.
1. Checking Authentication but Ignoring Authorization
A user may have a valid token but still lack permission to access a resource.
Every protected endpoint should enforce the appropriate authorization rules.
2. Trusting Client-Side Checks
Hiding an admin button in React.js does not secure the underlying API.
A user can call the endpoint directly using a tool such as Postman or a custom script.
Always enforce access control on the server.
3. Allowing Users to Modify Their Roles
Never grant administrative privileges simply because a request body contains:
{
"role": "admin"
}Role assignments should be controlled by trusted server-side logic and authorized administrative operations.
4. Forgetting Resource Ownership
Suppose a user can access:
GET /api/users/101Your application must not assume that every authenticated user can access every user ID.
Check whether the requested resource belongs to the user or whether the user has a separate permission to access it.
5. Storing Passwords in Plain Text
Passwords should be hashed using a suitable password-hashing algorithm before being stored.
Authentication systems should also protect against brute-force attempts and use MFA where appropriate.
Conclusion
Authentication and authorization are two fundamental concepts in application security.
Authentication verifies who a user is, while authorization determines what that user is allowed to do.
For example, when a user logs in to your MERN stack application, authentication verifies their identity. When the same user attempts to open an admin dashboard, authorization checks whether they have the necessary permissions.
As a Node.js developer, you should implement both concepts separately using authentication middleware, authorization middleware, and appropriate resource-level access checks.
Keeping these responsibilities separate helps you build REST APIs that are more secure, maintainable, and easier to scale.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


