How to Secure Your LoopBack REST API with JWT Authentication

Are you building dynamic REST APIs with LoopBack? In this tutorial, you'll learn how to implement user authentication and authorization in a Loopback REST API.
guest-post,loopback-rest-api-authentication
Table of Contents

What is LoopBack?

Authentication and authorization are critical in every software application to secure user data and allow access to trusted users. In some cases, implementing authentication and authorization is not an easy process.

However, LoopBack 4 offers an authentication package @loopback/authentication that helps secure your application's API endpoints. It provides custom authentication strategies and a @authenticate decorator that requires minimal boilerplate code.

What is LoopBack?

According to the LoopBack 4 documentation:

LoopBack is a flexible, open source Node.js and TypeScript framework built on Express. It helps you quickly develop APIs and microservices built on backend systems such as databases and SOAP or REST services.

Loopback provides several features that allow you to build your application with less boilerplate code.

What is JSON Web Token (JWT)?

JSON Web Token (JWT) is an open standard defined by Internet Engineering Task Force (IETF) in RFC 7519.

It is a standard used for securely transferring claims between two parties over the internet. It uses JSON Web Signature (JWS) for the secure transfer of claims and eliminates the possibility of tampering. Accordingly, JWTs can be signed with either a secret (HMAC technique) or a public/private key pair (RSA or ECDSA).

In simple words, it is used for authentication and secure information sharing. A JWT token is made up of three components that are separated by three dots:

  • Header: The header is made up of two parts — the kind of token, which is JWT; the signature technique used, either HMAC SHA256 or RSA.
  • Payload: The payload is the token, which includes the claims. Claims are assertions about an entity that provides extra information.
  • Signature: The encoded header, encoded payload, a secret, and the algorithm provided in the header comprise the signature.

You can learn more about JWT and its best practices here.

Prerequisites

This tutorial is a hands-on demonstration. To follow along, be sure you have the following in place:

  • A Linux machine — This tutorial will use Ubuntu 20.04.3 LTS (Focal Fossa). The tutorial also works well on other Linux distributions and operating systems.
  • NodeJS — JavaScript runtime built on Chrome's V8 JavaScript engine.
  • MongoDB — Document-oriented database program.

Install LoopBack CLI

To start building your LoopBack REST API, first install LoopBack CLI, which provides the quickest method to create a LoopBack 4 project that follows best practices.

Use the command below to install the Loopback CLI globally:

You can grab a cup of coffee while you wait for the installation to complete. Then open your command line, create an folder, and change the directory to the folder with commands below:

Scaffold Your LoopBack Project

So, you've installed Loopback CLI and created a project directory. Let's run the following command to create a LoopBack project:

Select the options as in the following screenshot to complete the prompts.

Creating a loopback project

After completing the prompts, LoopBack will configure the TypeScript compiler and install all the required dependencies. Change directory to the folder.

Create a Model

You've successfully created your Loopback application. Now, let’s create a Model to store the news details with the command below:

Select the options as in the following screenshot to complete the prompts.

Creating a News Model

After the property definition, press the enter key to exit the prompt.

Loopback will create a file in the — the folder where will be defined.

Next, you need to create a data source to connect to your preferred database. For demonstration, this tutorial connects to a MongoDB database.

Run the following command in your terminal to create a data source:

Select the options as in the following screenshot to complete the prompts.

Creating News datasource

After completing the prompts, LoopBack will create the file in the folder.

Then, create a Repository for CRUD operations of your NewModel with the command below:

After completing the prompts, LoopBack will create the file in the folder.

Select as the data source, as the model for generating the repository, and as the base repository class.

Your selection for the prompts shall look like the screenshot below.

Creating News Repository

After completing the prompts, LoopBack will create the file in the folder.

Lastly, create a controller for the you created with the command below:

Your selection for the prompts should look like the screenshot below.

Creating News Controller

After completing the prompts, LoopBack will create the file in the folder. So far, your project structure, omitting the folder, should look as follows.

📦auth-with-loopback
┣ 📂public
┃ ┗ 📜index.html
┣ 📂src
┃ ┣ 📂tests
┃ ┃ ┣ 📂acceptance
┃ ┃ ┃ ┣ 📜home-page.acceptance.ts
┃ ┃ ┃ ┣ 📜ping.controller.acceptance.ts
┃ ┃ ┃ ┗ 📜test-helper.ts
┃ ┃ ┗ 📜README.md
┃ ┣ 📂controllers
┃ ┃ ┣ 📜README.md
┃ ┃ ┣ 📜index.ts
┃ ┃ ┣ 📜news-controller.controller.ts
┃ ┃ ┗ 📜ping.controller.ts
┃ ┣ 📂datasources
┃ ┃ ┣ 📜README.md
┃ ┃ ┣ 📜index.ts
┃ ┃ ┗ 📜news.datasource.ts
┃ ┣ 📂models
┃ ┃ ┣ 📜README.md
┃ ┃ ┣ 📜index.ts
┃ ┃ ┗ 📜news-model.model.ts
┃ ┣ 📂repositories
┃ ┃ ┣ 📜README.md
┃ ┃ ┣ 📜index.ts
┃ ┃ ┗ 📜news-model.repository.ts
┃ ┣ 📜application.ts
┃ ┣ 📜index.ts
┃ ┣ 📜migrate.ts
┃ ┣ 📜openapi-spec.ts
┃ ┗ 📜sequence.ts
┣ 📜.dockerignore
┣ 📜.eslintignore
┣ 📜.eslintrc.js
┣ 📜.gitignore
┣ 📜.mocharc.json
┣ 📜.prettierignore
┣ 📜.prettierrc
┣ 📜.yo-rc.json
┣ 📜DEVELOPING.md
┣ 📜Dockerfile
┣ 📜README.md
┣ 📜package-lock.json
┣ 📜package.json
┗ 📜tsconfig.json

Add Custom Data

Now that you have the Model setup, run the server, and add some custom data to the News collection in MongoDB.

The above command will start the TypeScript compiler, which will build the project and check for possible errors. If everything goes well with the code, you should see the output on the terminal, as follows:

Starting LoopBack Server

Next, open your favorite browser and navigate to . You should see an output as follows:

LoopBack API Dashboard

Now, click on the explorer link, where you can make requests to your LoopBack application. On the explorer page, locate the post endpoint and add some custom data to the news collection by clicking the button with the data below on the request body.

Then, click the button to run the query.

Executing Queries

You can add as many records as you like to experiment with the endpoints. The important thing to note here is that the endpoints are not protected. Anyone may create, read, update, and delete records.

In a moment, this tutorial explains how to secure the endpoints so that only logged-in users can access them.

To begin, install LoopBack and , as follows:

Setup Authentication Components

To protect the application, you'll implement user authentication and authorization, which implies that only logged-in users will be able to access your APIs. You'll create two endpoints in the User controller:

  • endpoint: To handle user’s sign up.
  • endpoint: To handle user’s login.

Create Your Signup Endpoint

You’ll start with the signup controller to enable users to create an account. Create an empty controller with the command below:

Your selection for the prompts should be as follows:

Creating User Controller

Then, open the file, and import the required modules with the following code snippet:

Next, set up your user credential objects, and verify the user credentials using the , injecting into the extension.

Finally, you'll build your signup endpoint, which will listen to POST requests. Here, you shall save the hashed version of the user's password in the database to keep it safe.

Create Your Login Controller

Now that you've set up the signup endpoint, create the login endpoint so that registered users may log in to the API.

Using the code snippet below, set up the login route in the file. In the event of a successful log-in, a token is sent to the user.

Perhaps, you can show the currently logged-in user by adding a endpoint.

In the file, get the details of the currently logged-in user using the code snippet below. Users should access this endpoint only when they are logged in.

Now, open and bind the authentication components to your application class. First, import Loopback , , and from your using the following code snippet:

Then, mount the jwt authentication system and bind your to the data source.

Finally, add the authenticate action in the Sequence. Also, modify the error when authentication fails to return status code 401 (Unauthorized). Open the file and add the code snippet below:

Protect News Endpoints

So far, you've implemented user authentication for your API. Now, protect your News endpoints so that only authenticated users can access those routes.

Open the file, and import from jwt authentication.

Then on each of the endpoints in your news controller, add before the class, which will protect all the routes in .

Perhaps, you may not want to protect all the routes, simply add the method before the route you wish to protect. You can protect the POST route as follows:

Test Your Application

You've implemented user authentication in your REST API and secured the routes against unauthorized users. Let's put your application to the test. Press to exit the server and restart it with the following command:

If you open the explorer page, you should see the endpoints.

User Controller Endpoints

If you try to execute any query on , you get a 404 (Unauthorized) error. So, sign up by clicking the endpoint — and log in from the endpoint. On successful login, copy the token, scroll to the top, click on the button, and paste the token.

Authorizing Users

Now you can execute queries on the endpoints.

User Authentication with Loginradius

LoginRadius is a customer identity and access management (CIAM) platform for developers.

What does this mean for developers like you?

LoginRadius simplifies the process of user authentication, authorization, and management across web and mobile apps and APIs. It helps developers quickly implement this functionality so that developers, like you, can focus more on building core features that are essential to their apps.

Loginradius includes a plethora of enticing CIAM features such as passwordless authentication and social SSO (Twitter, Facebook, etc., based single sign-on).

Implementing user authentication with LoginRadius is a simple procedure. First, sign up for a Developer Pro trial or simply sign up for a forever free account here.

And you can explore what LoginRadius can do by using it for a Node.js application. You can learn more by going through LoginRadius Node.js developer documentation

Conclusion

This tutorial taught you how to create user authentication in a LoopBack REST API by creating a small news database application.

You can use the steps outlined in this tutorial to create any type of LoopBack REST API that requires user authentication and authorization.

I hope you enjoyed this tutorial! Feel free to contact me on Twitter.

Ekekenta Odionyenfe Clinton
By Ekekenta Odionyenfe ClintonHe is a full-stack web application developer, software engineer, and technical writer, currently living in Nigeria, Portharcourt. He has an HND in Computer Science from Federal Polytechnic Nekede. His primary focus and inspiration for his studies is web development. In his free time, he studies human psychology and writes technical tutorials.
Featured Posts

How to Implement JWT Authentication for CRUD APIs in Deno

Multi-Factor Authentication (MFA) with Redis Cache and OTP

Introduction to SolidJS

Build a Modern Login/Signup Form with Tailwind CSS and React

Implement HTTP Streaming with Node.js and Fetch API

NestJS: How to Implement Session-Based User Authentication

NestJS User Authentication with LoginRadius API

How to Authenticate Svelte Apps

Flutter Authentication: Implementing User Signup and Login

How to Secure Your LoopBack REST API with JWT Authentication

Node.js User Authentication Guide

Your Ultimate Guide to Next.js Authentication

Local Storage vs. Session Storage vs. Cookies

How to Secure a PHP API Using JWT

Using JWT Flask JWT Authentication- A Quick Guide

Build Your First Smart Contract with Ethereum & Solidity

What are JWT, JWS, JWE, JWK, and JWA?

How to Build an OpenCV Web App with Streamlit

32 React Best Practices That Every Programmer Should Follow

How to Build a Progressive Web App (PWA) with React

Bootstrap 4 vs. Bootstrap 5: What is the Difference?

JWT Authentication — Best Practices and When to Use

What Are Refresh Tokens? When & How to Use Them

How to Upgrade Your Vim Skills

How to Implement Role-Based Authentication with React Apps

How to Authenticate Users: JWT vs. Session

How to Use Azure Key Vault With an Azure Web App in C#

How to Implement Registration and Authentication in Django?

11 Tips for Managing Remote Software Engineering Teams

Implementing User Authentication in a Python Application

Add Authentication to Play Framework With OIDC and LoginRadius

Share On:
Share on TwitterShare on LinkedIn