In a website using JWT based authentication. Lets say we have multiple users in database such as A and B. The api call called fetch/user/ should return user's data from database based upon the param. Also, as this API is called after authentication, the user sends JWT as Auth header.
Now lets consider this scenario. I as User A log into the website. I call /fetch/user/A to get my data. I inspect the Chrome dev tools and copy my JWT.
I open POSTMAN, then put the request as /fetch/user/B and use my auth JWT token.
To my surprise, it returns the data of user B.
Expectation user A's JWT should not return data for any other user. Seems like only JWT gets verified, not user specific data. Considering that the basic JWT setup is used as shown in multiple JWT tutorial pages, how do we resolve this issue?
The issue you're encountering is a common problem when implementing JWT-based authentication. The fundamental problem is that your backend API is not verifying that the user making the request has the correct authorization to access the specific data they are requesting, and the responsibility for solving this problem falls on the back-end developer, and they can solve it by creating Middleware to Authenticate and Authorize the User.
function authorizeUser(req, res, next) {
const requestedUserId = req.params.userId; // assuming userId is a route parameter
const loggedInUserId = req.user.sub;
if (requestedUserId !== loggedInUserId) {
return res.status(403).json({ message: 'You are not authorized to access this resource' });
}
next();
}