Using JWT token for authentication in nodeJS

Stephens Xu
Fullstack Network
Published in
3 min readJul 13, 2017

--

Last night in the live streaming we worked on user authentication for the Pomidori Project.

If you’re like me that’s not very familiar with how JWT works, this is a good article to read into that makes some good point about token vs cookie authentications.

Anyhow, the goal is that once a user registers with the server and wants to make additional API call in the future, we would like to have a stateless token that the server can use to authenticate this user.

We are using jsonwebtoken for encoding and decoding jwt tokens.

The authentication cycle starts with the registration of a new user, which creates a new user object. Now we would like to create a jwt based on user id like so:

import jwt from 'jsonwebtoken';const token = jwt.sign({
userId: user._id,
}, "FAKE_SECRET");
passport.authenticate('local')(req, res, () => {
const responseObject = Object.assign({}, { user }, { token })
res.json(responseObject)
})

Notice here we are signing the jwt with two variables, user._id and a place holder “FAKE_SECRET”. In production this “FAKE_SCRET” would be replaced by a secret or private key of your own choice.

And then the client gets a response containing both the token and user object as json:

Now the client has the jwt token. This token contains all the information the server needs to identify a user. Let’s say we want to make an API request to the /api/task endpoint with this token, we expect the server to know which user made this request, authenticate and return tasks that’s associated with this user only. The client need to put this token in “Authorization” field of request header, like so:

Note here the we append the string “JWT” with a space at beginning of the full token.

In the server, we decode the token like so:

import { ExtractJwt } from 'passport-jwt'function create(req, res, next) {
const token = ExtractJwt.fromAuthHeader()(req);
const decoded = jwt.verify(token, 'FAKE_SECRET');

const taskObject = {
taskTime: req.body.taskTime,
title: req.body.title,
userId: decoded.userId,
};

TaskFactory.create(taskObject).then((result) => {
res.json(result)
});
}

Notice here the decoded content of jwt would give us the userId directly, this is one of the key benefit of using jwt, because we already know the userId here without querying the database at all!

And after authenticated successfully, server responds with the task object associated with this userId:

Hope this helps you to understand JWT a little bit more.

Join us in our next streaming session here if it interest you!

--

--