Making an Authenticated Route

Learn to use middleware to validate the JWT and allow the authenticated users.

We'll cover the following

Add JWT middleware route

Having the capacity to get users a token, we now want a guarantee that only logged-in users can access the museum route.

Users will have to send the token in the Authorization header because the JWT token standard defines. If the token is invalid or not present, the user should be presented with a 401 Unauthorized status code.

Validating the token that’s been sent by users on the request is a nice use case for middleware functions.

In order to do this, and since we’re using Oak, we’ll be using a third-party module named oak-middleware-jwt. This is nothing more than a middleware that automatically validates the JWT, based on a key, and provides functionality that will be useful to us.

You can check its documentation at https://nest.land/package/oak-middleware-jwt.

Let’s use this middleware in our web code to make the museums route only available to authenticated users. Follow these steps:

  1. Add oak-middleware-jwt to the deps.ts file, and export the jwtMiddleware function:

Get hands-on with 1400+ tech skills courses.