Skip to content

Commit 10a0cd0

Browse files
committed
Query DB for user details
Closer parallel with sessions example, only omitting DB query for session
1 parent 8f1d4d7 commit 10a0cd0

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

nodeJS/authentication/json_web_tokens.md

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,14 +73,24 @@ The client must attach the JWT to any such requests, whether that's through `fet
7373
// in an authentication middleware
7474
const token = req.get("authorization")?.split(" ")[1];
7575
try {
76-
req.user = jwt.verify(token, process.env.SECRET);
76+
const { id } = jwt.verify(token, process.env.SECRET);
77+
const { rows } = await pool.query(
78+
"SELECT * FROM users WHERE id = $1",
79+
[id],
80+
);
81+
const user = rows[0];
82+
req.user = {
83+
// whatever user details may be needed for any requests
84+
}
7785
next();
7886
} catch (err) {
7987
res.status(401).json("Could not authenticate user");
8088
}
8189
```
8290
83-
Upon successful verification, the payload is returned and can be handled however necessary; in the example above, it gets attached to `req` and the next middleware is called. If the token is not valid, whether that's from it having expired or not valid or even non-existent, an error is thrown which we can catch and unauthorize the request, responding to the client with a 401 since we do not know who they are.
91+
Upon successful verification, the payload is returned and can be handled however necessary; in the example above, we query our database for the right user details, assign what we need to `req.user`, then the next middleware is called. If the token is not valid, whether that's from it having expired or not valid or even non-existent, or if the user no longer exists, an error is thrown which we can then catch and unauthorize the request, responding to the client with a 401 since we do not know who they are. The authentication and database query can also be handled in separate middleware functions if you wish.
92+
93+
Essentially, this is a similar process to our previous session-based authentication system only since the authentication data came with the JWT payload, we did not need to make an additional database call to grab that data from a session.
8494
8595
### Assignment
8696

0 commit comments

Comments
 (0)