Basic user authentication in express — Part 2

Aditya Naik
Nomads Of Code
Published in
5 min readJun 29, 2020

Using passport-jwt strategy.

Photo by Masaaki Komori on Unsplash

This is Part 5 of multi-part series on ExpressJS.

You can find Part 1 here. It talks about building a basic express api and setting up mocha for testing.

You can find Part 2 here. It talks about setting up PostgreSQL, sequelize for connecting express api with databases.

You can find Part 3 here. It talks about setting up associations (has many as well as belongs to) between two models.

You can find Part 4 here. It talks about setting up user authentication based on email and password.

Our Plan of attack —

  • When we login — create and send a JWT in response
  • When we hit a protected route, JWT — sent as a part of request header — is decoded to extract user information
  • Unauthorized request, without JWT, gets rejected with 401 status

Let’s handle the first point first —

Update tests for login

Since we are expecting to receive a token after logging in, we should update our tests to verify that.

We expect response.body to be an object which contains a token for us to use.

Create and set token

We then update our passport-local strategy, in order to create and send across a JWT whenever a user logs in.

First we install JSON web token packagenpm i jsonwebtoken

Then, we go to our auth/index.js where we have our login route handling logic.

We import jsonwebtoken at the top of the file.

Now we can use jwt to ‘sign’ the token.

We will use user email as JWT payload.

Payload is the information we want to be saved in the token, and it is available after we receive and decode the token for other requests.

This creates a token using jwt.sign() method available to us and sends it across as a response for valid passport-local authentication.

This is how our updated auth/index.js looks —

This is exactly what we are looking for in our test, and it should go green for us.

Time to use this token and set up a protected route.

We will build another route to GET /user endpoint, and we will protect it.

Write a test for user route

We know we want to protect GET /user endpoint, and return 401 status if token is missing from any request.

We login first, and save the token we receive as response. Then we attach the saved token as Authorization header to get a valid response.

We also check if response is 401 in case the token is missing.

We can update our seeds to make sure only the posts for the author are being sent —

So totally we create 8 posts, and 2 authors. Each of the author has 4 posts associated.

We also update our posts.spec.js to check for 8 posts.

Set up passport JWT strategy

Install the package

npm i passport-jwt

Add a file auth/passport-jwt.js where we will set up our logic

We define a new Strategy() where we take in decoding choice and secret from the options. We extract payload from incoming request JWT, and find the user with the email from the payload.

If user is found, we attach it to the req object and then it is available as req.user .

For reference, we can use different methods for ExtractJwt depending on how the client is sending across the token.

Create a user route, import it and protect it with passport

Now we have logic set up, time to build the route and protect it.

Add a controllerusers.js first —

Then connect it with routes/users.js route —

and import the route and use it within app.js

First —

Then —

Route is now connected, and tests will go green!

Exploring JWT

If we intercept JWT midflight, for eg. console logging/debugging in user route test, we will get something that looks like this —

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImF1dGhvckBtYWlsLmNvbSIsImlhdCI6MTU5MzQzNjcxMywiZXhwIjoxNTkzNDcyNzEzfQ.uTHjn39zcoSGWdFklAtWCsSO66K2FeCmcM-ORFMAJ2M

We can visit JWT.io and decode the token to look inside —

We can see that the token has a payload containing email, and much more apart from that.

In next part of the series, we will take a look at many-to-many relationships using sequelize.

Craft Academy is a Tech Education Provider that aims to bring new talent to the market and help to solve the shortage of tech workers. We are founded on the belief that modern development standards, agile methodologies, and business skills are fundamental for IT professionals.

Our primary service is a 12-week coding bootcamp designed to provide individuals with a foundation of skills that allows them to enter the industry as junior developers.

With that foundation, our learners find employment in various industries or start their own businesses that bring new innovations to the market.

Would you like to know more about what we do? Follow us here on Medium, Facebook, Twitter or visit our website.

--

--