DEV Community

Ethern Myth
Ethern Myth

Posted on • Updated on

Adding JWT Auth on Node.js the easy way

JWT are a quick way to lock a small API for access and authentication. By doing it right, even on large project, JWT can be of use. Right here, I detail a utility I created and use.

This utility is injected in the header method when a bearer token is sent. Bearer token are authentication token passed over the HTTP Client authentication scheme.

*Here is the code for the utility:
*

Header Token

You can implement this code in your library code for easier global access.

Install from npm:

npm install ensure-token

Or visit Ensure-Token

Ensure Token

The code simply says 😂, of course code speaks too. Get the bearer token from the upcoming request from the header tag, specifically look for authorization. Check if the bearer token is not of type undefined since the request will be a string encoded. Undefined means on the if statement, there is no bearer token passed with the request, incase the bearer token is empty, else, split where there's bearer token whitespace and save. This will save an array. Then get the second item, from the array. Remember arrays begin at 0 index, so we want the other long string. Example of bearer token passed including bearer token keyword:

Authorization: Bearer <token>

With that continues, The variable that holds the token is then inserted to the whole of the current request. Then next(); is invoked. The next method executes the next middleware in the middleware stack, which is of express not our custom middleware.

Else if we have an undefined, we handle this by serving a status 403. 403 is forbidden status for invalid access.

That's about for the header token utility.

Implementing this on your route is easy as this for express.

Implemented header token

Just by adding ensureToken after the route name, the route is secured for authentication.

On the next blog, I will discuss jwt login and getting the token with the login.

I hope to hear from you about this approach and if there's a better way to improve the implementation.

Thanks 🥷

Top comments (0)