How to Build an Authentication API with JWT Token in Node.js
June 15, 2021- Topics:
- Node.js
In this tutorial, we will learn how to use JWT in Node.js to secure endpoints and even authenticate users.
Its pretty simple to write code and develop applications. Yet, how do we deal with authentication, and most likely, authorization?
What is authentication and authorization
Authentication and authorization are used in security, particularly when it comes to getting access to a system. Yet, there is a significant distinction between gaining entry into a house [authentication] and what you can do while inside [authorization].
Authentication
Authentication is the process of verifying a users identification through the acquisition of credentials and using those credentials to confirm the users identity. The authorization process begins if the credentials are legitimate. The authorization process always follows the authentication procedure.
You were already aware of the authentication process because we all do it daily, whether at work [logging into your computer] or at home [logging into a website]. Yet, the truth is that most things connected to the Internet require you to prove your identity by providing credentials.
Authorization
Authorization is the process of allowing authenticated users access to resources by determining whether they have system access permissions. By giving or denying specific licenses to an authenticated user, authorization enables you to control access privileges.
So, authorization occurs after the system authenticates your identity, granting you complete access to resources such as information, files, databases, funds, places, and anything else. That said, authorization affects your capacity to access the system and the extent to which you can do so.
What is JWT
JSON Web Tokens [JWT] are an RFC 7519 open industry standard for representing claims between two parties. For example, you can use jwt.io to decode, verify, and produce JWT.
JWT specifies a compact and self-contained method for communicating information as a JSON object between two parties. Because it is signed, this information can be checked and trusted. JWTs can be signed using a secret [using the HMAC algorithm] or an RSA or ECDSA public/private key combination. In a moment, well see some examples of how to use them.
Prerequisites
To follow along with this tutorial, you will need:
- A working knowledge of JavaScript.
- A good understanding of Node.js.
- A basic understanding of MongoDB or any database of your choice.
- Postman and some knowledge on how to use Postman.
API development using JWT token for authentication in Node.js
To get started, well need to set up our project.
Open Visual Studio Code by navigating to a directory of your choice on your machine and opening it on the terminal.
Then execute:
Note: code . wont work if you dont have Visual Studio Code installed on your system.
Step 1 - Create a directory and initialize npm
Create a directory and initialize npm by typing the following command:
- Windows power shell
- Linux
Step 2 - Create files and directories
In step 1, we initialized npm with the command npm init -y, which automatically created a package.json.
We need to create the model, middleware, config directory and their files, for example user.js,auth.js,database.js using the commands below.
We can now create the index.js and app.js files in the root directory of our project with the command.
As shown in the image below:
Step 3 - Install dependencies
Well install several dependencies like mongoose, jsonwebtoken, express dotenv bcryptjs and development dependency like nodemon to restart the server as we make changes automatically.
We will install mongoose because I will be using MongoDB in this tutorial.
We will validate user credentials against what we have in our database. So the whole authentication process is not limited to the database well be using in this article.
Step 4 - Create a Node.js server and connect your database
Now, lets create our Node.js server and connect our database by adding the following snippets to your app.js, index.js , database.js .env in that order.
In our database.js.
config/database.js:
In our app.js:
jwt-project/app.js
In our index.js:
jwt-project/index.js
If you notice, our file needs some environment variables. You can create a new .env file if you havent and add your variables before starting our application.
In our .env.
To start our server, edit the scripts object in our package.json to look like the one shown below.
The snippet above has been successfully inserted into app.js, index.js, and database.js. First, we built our node.js server in index.js and imported the app.js file with routes configured.
Then, as indicated in database.js, we used mongoose to create a connection to our database.
Execute the command npm run dev.
Both the server and the database should be up and running without crashing.
Step 5 - Create user model and route
Well define our schema for the user details when signing up for the first time and validate them against the saved credentials when logging in.
Add the following snippet to user.js inside the model folder.
model/user.js
Now lets create the routes for register and login, respectively.
In app.js in the root directory, add the following snippet for the registration and login.
app.js
Step 6 - Implement register and login functionality
Well be implementing these two routes in our application. We will be using JWT to sign the credentials and bycrypt to encrypt the password before storing them in our database.
From the /register route, we will:
- Get user input.
- Validate user input.
- Validate if the user already exists.
- Encrypt the user password.
- Create a user in our database.
- And finally, create a signed JWT token.
Modify the /register route structure we created earlier to look as shown below.
app.js
Note: Update your .env file with a TOKEN_KEY, which can be a random string.
Using Postman to test the endpoint, well get the response shown below after successful registration.
For the /login route, we will:
- Get user input.
- Validate user input.
- Validate if the user exists.
- Verify user password against the password we saved earlier in our database.
- And finally, create a signed JWT token.
Modify the /login route structure we created earlier to look like shown below.
Using Postman to test, well get the response shown below after a successful login.
Step 7 - Create middleware for authentication
We can successfully create and log in a user. Still, well create a route that requires a user token in the header, which is the JWT token we generated earlier.
Add the following snippet inside auth.js.
middleware/auth.js
Now lets create the /welcome route and update app.js with the following snippet to test the middleware.
app.js
See the result below when we try to access the /welcome route we just created without passing a token in the header with the x-access-token key.
We can now add a token in the header with the key x-access-token and re-test.
See the image below for the response.
You can click here to check the complete code on GitHub.
Conclusion
In this tutorial we learned about JWT, authentication, authorization and how to develop an API using JWT token for authentication in Node.js.
Happy coding!
Resources
- JWT
- Node.js
- ExpressJS
Peer Review Contributions by: Geoffrey Mungai
About the author
Idris Olubisi is a software developer, technical writer and speaker skilled at problem-solving, technical leadership, communications, and presentations with vast experience in full project life cycle.
- Follow @olanetsoft
- Connect on LinkedIn
- Follow @Olanetsoft on GitHub