Introduction
When building a web application or REST API, it is not enough to verify that a user is logged in. You also need to decide what that user is allowed to do.
For example, a regular user may be allowed to view their profile, while an administrator may be allowed to manage users, delete records, or access an admin dashboard.
This is where JWT authorization becomes useful. JSON Web Tokens (JWTs) can carry information about a user’s identity and role. After verifying the token, the server can use that information to decide whether the user can access a particular resource.
In this tutorial, you will learn how JWT authorization works in Node.js, how it differs from authentication, and how to implement role-based access control using Express.js and the jsonwebtoken package.
What Is JWT Authorization?
JWT authorization is the process of deciding whether a user with a valid JSON Web Token has permission to access a resource or perform an action.
A JWT may contain claims such as a user’s ID, role, or other relevant information. When a client sends the token to the server, the server verifies its signature and checks the user’s permissions before allowing access.
For example, an application might define these permissions:
- User: View their own profile.
- Editor: Create and update articles.
- Admin: Manage users and access administrative features.
A JWT can help identify the user’s role, but the application must still enforce the appropriate permissions on the server.
JWT Authentication vs JWT Authorization
| Authentication | Authorization |
|---|---|
| Verifies who the user is. | Determines what the user can access. |
| Usually happens during login or token validation. | Happens when the user requests a protected resource or action. |
| Example: checking a user’s credentials. | Example: checking whether the user has the admin role. |
| Answers, “Who are you?” | Answers, “What are you allowed to do?” |
Authentication and authorization are related, but they serve different purposes.
For example, when a user logs in, the server may issue a JWT after validating their credentials. When that user requests /admin/users, the server verifies the token and then checks whether the user has the required role.
A valid token does not automatically grant permission to access every endpoint.
How JWT Authorization Works
JWT authorization generally follows these steps:
- The user logs in with valid credentials.
- The server creates a JWT containing relevant claims, such as the user’s ID and role.
- The client sends the token with a request to a protected API.
- The server verifies the token’s signature and expiration.
- Authorization middleware checks the user’s role or permissions.
- The server allows the request or returns an appropriate error.
For example, an administrator can access an admin-only route, while a regular user receives a 403 Forbidden response.
Prerequisites
Before implementing JWT authorization in Node.js, make sure you have:
- Node.js and npm installed.
- Basic knowledge of JavaScript.
- Basic understanding of Express.js.
- Familiarity with JWT authentication.
You will use the following packages:
- express to create the API.
- jsonwebtoken to create and verify JWTs.
- dotenv to load environment variables.
Step 1: Create a Node.js Project
Create a project directory and initialize it:
mkdir jwt-authorization
cd jwt-authorization
npm init -y
Install the required packages:
npm install express jsonwebtoken dotenv
Create a file named .env in the project directory:
PORT=3000
JWT_SECRET=replace_with_a_long_random_secret
Replace the example secret with a strong, randomly generated secret. Do not commit the .env file to a public repository.
Step 2: Generate a JWT with a User Role
When a user successfully logs in, the server can create a token containing the user’s ID and role.
The following is a simplified example of token creation:
const jwt = require('jsonwebtoken');
function createToken(user) {
return jwt.sign(
{
role: user.role
},
process.env.JWT_SECRET,
{
subject: String(user.id),
expiresIn: '1h',
algorithm: 'HS256'
}
);
}
const token = createToken({
id: 101,
role: 'admin'
});
console.log(token);
In this example, the token contains the user’s role and uses the user’s ID as the JWT subject.
Important: This snippet demonstrates token creation only. In a real application, the user object must come from a trusted source after the server has verified the user’s credentials. Never accept a role supplied by the client as proof of authorization.
JWT payloads are encoded, not encrypted by default. Do not store passwords, API secrets, or other sensitive information in them.
Step 3: Verify the JWT
Before checking a user’s permissions, the server must verify the token.
Create a file named server.js:
require('dotenv').config();
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json());
function authenticateToken(req, res, next) {
const authHeader = req.headers.authorization;
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({
message: 'Access token is required'
});
}
jwt.verify(
token,
process.env.JWT_SECRET,
{ algorithms: ['HS256'] },
(err, decoded) => {
if (err) {
return res.status(401).json({
message: 'Invalid or expired token'
});
}
req.user = {
id: decoded.sub,
role: decoded.role
};
next();
}
);
}
The authenticateToken() middleware extracts the Bearer token from the Authorization header and verifies its signature and expiration.
If verification succeeds, the middleware attaches the relevant user claims to req.user. If the token is missing or invalid, the request is rejected with 401 Unauthorized.
This middleware verifies the token; it does not yet decide whether the user has permission to access a particular route.
Step 4: Create Role-Based Authorization Middleware
Now create middleware that checks whether the authenticated user has the required role.
Add the following function to server.js:
function authorizeRoles(...allowedRoles) {
return (req, res, next) => {
if (!req.user) {
return res.status(401).json({
message: 'Authentication is required'
});
}
if (!allowedRoles.includes(req.user.role)) {
return res.status(403).json({
message: 'You do not have permission to access this resource'
});
}
next();
};
}
The authorizeRoles() function accepts one or more permitted roles.
For example:
authorizeRoles('admin')
allows only users whose verified token contains the admin role.
You can also permit more than one role:
authorizeRoles('admin', 'editor')
This allows both administrators and editors to access the route, assuming their role claims are valid and current under your application’s authorization policy.
Step 5: Protect Routes Using JWT Authorization
You can now combine authentication and authorization middleware to protect API endpoints.
Add these routes to server.js:
app.get('/profile', authenticateToken, (req, res) => {
res.json({
message: 'Profile accessed successfully',
user: req.user
});
});
app.get(
'/admin',
authenticateToken,
authorizeRoles('admin'),
(req, res) => {
res.json({
message: 'Welcome to the admin dashboard'
});
}
);
app.get(
'/editor',
authenticateToken,
authorizeRoles('admin', 'editor'),
(req, res) => {
res.json({
message: 'Welcome to the editor dashboard'
});
}
);
app.listen(process.env.PORT || 3000, () => {
console.log('Server is running');
});
The complete example now includes three routes:
- /profile requires a valid JWT.
- /admin requires a valid JWT and the admin role.
- /editor requires a valid JWT and either the admin or editor role.
Notice the middleware order: authenticateToken runs before authorizeRoles, ensuring that the role check uses claims from a verified token.
Step 6: Test JWT Authorization
Start the server:
node server.js
To test the protected routes, you need a valid token. For a quick local test, use the token generated by the earlier createToken() example with the same JWT_SECRET.
Send the token in the HTTP request header:
Authorization: Bearer YOUR_JWT_TOKEN
You can test the routes with Postman or curl.
Access the profile route:
curl http://localhost:3000/profile \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
Access the admin route:
curl http://localhost:3000/admin \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
If the token contains the admin role and passes verification, the admin route returns a successful response. If the token contains a different role, the server returns 403 Forbidden.
The token-generation snippet is a separate demonstration; the server above does not include a login endpoint. In a real application, issue tokens only after validating credentials against your user database.
401 Unauthorized vs 403 Forbidden
These HTTP status codes are important when implementing JWT authorization.
These HTTP status codes are important when implementing JWT authorization.| Status Code | Meaning | Example |
|---|---|---|
401 Unauthorized |
Authentication is missing or invalid. | The request has no token or the token has expired. |
403 Forbidden |
The user is authenticated but lacks permission. | A regular user tries to access an admin-only endpoint. |
JWT Authorization Best Practices
Follow these practices when implementing JWT authorization in a real application.
1. Verify Every Protected Request
Do not trust a token simply because the client sends it. Verify its signature, expiration, and expected signing algorithm on the server.
2. Never Trust Client-Supplied Roles
Do not authorize requests using a role sent separately in a request body or query parameter. Assign roles from a trusted database or another trusted server-side source when issuing tokens.
3. Keep Token Lifetimes Appropriate
Use reasonable expiration periods for access tokens. For sensitive applications, consider short-lived access tokens and a carefully designed refresh-token strategy.
4. Consider Role Changes and Token Revocation
A role embedded in a JWT can become outdated before the token expires. If an administrator removes a user’s privileges, an already-issued token may still contain the old role.
For sensitive actions, check current permissions in the database or use a revocation/versioning strategy.
5. Use HTTPS
HTTPS protects tokens while they travel between the client and server. Avoid sending JWTs in URLs because URLs can appear in browser history, server logs, and referrer data.
6. Protect JWT Secrets
Use a strong, randomly generated secret and store it in environment variables or a secrets manager. Never expose it in client-side code or public repositories.
7. Check Resource Ownership
Roles alone may not be enough. For example, a user may be allowed to view their own profile but not another user’s profile. Check resource ownership or specific permissions where necessary.
8. Use Appropriate Token Storage
Choose token storage based on your application’s architecture and threat model. Browser storage, cookies, and server-side sessions have different security trade-offs. If using cookies, configure appropriate HttpOnly, Secure, and SameSite attributes and protect against cross-site request forgery where relevant.
Common Mistakes in JWT Authorization
Avoid these common errors:
- Checking the role without verifying the token: Always authenticate first.
- Treating every valid token as an admin token: Authentication does not automatically grant administrative access.
- Putting sensitive data in the JWT payload: Payload data is generally readable by anyone who obtains the token.
- Using a weak signing secret: A weak secret can make token forgery easier.
- Ignoring role changes: A token can retain outdated claims until it expires unless your application checks current permissions or revocation status.
- Confusing 401 and 403: Use 401 for missing or invalid authentication and 403 for insufficient permission.
- Allowing users to choose their own roles: Roles must be assigned and verified by trusted server-side logic.
Conclusion
JWT authorization in Node.js helps protect APIs by checking what an authenticated user is allowed to access. Using Express.js and the jsonwebtoken package, you can verify JWTs with authentication middleware and enforce role-based access with authorization middleware.
For a production application, combine JWT verification with trusted role assignment, resource-level permission checks, secure token handling, and a strategy for handling expired or revoked tokens. These measures help ensure that users can access only the resources and actions permitted by your application.