How to set-up Basic Auth on a Node.js project

In this tutorial, we are going to integrate Basic Auth using the Mockless low-code Studio.

Setup basic auth on Mockless Studio

The focus of this tutorial will be on setting up Basic Auth on a Node.js project and applying it to some sensitive REST endpoints.


This tutorial uses an already created Node.js project that was described here.
In case you are not familiar with Mockless Studio or you don’t have any Mockless projects yet, we encourage you to create your first project as we described here.

To successfully follow this tutorial you will have to have an account on Mockless Studio.

Activating the Basic Auth plugin on Mockless Studio

In Mockless Studio, adding Basic Auth support is as simple as enabling a plugin. Once the plugin is enabled you will be able to add the required source code to protect specific routers with a username and a password.

The first step would be to go on the Security page under the Marketplace section and click to add the Basic Auth plugin as shown below:

Applying security rules to the REST endpoint

Once the plugin is enabled, the auth method will be available on the Routers and Flows sections and you can decide which endpoints to be protected by this authorization method.

In this example, we have added only on the POST /articles endpoint but would be required to be added on every sensitive endpoint.

Updating the environment

The Basic Auth credentials are stored based on the environment in which the API is started. As we already have a local environment, all you have to do is to edit it and set the proper username and password under the Secrets section.

Testing the auth flow

After you build your project in Mockless Studio, a new commit will be pushed to your git repository containing all the changes to make the Basic Auth method working.

After you pull the code changes, you will have to rebuild and restart your project.

npm run build
npm run local:express:start

Now you cannot post articles anymore without passing the proper Basic Auth credentials on your request.

Your request should be made like this:

 curl \
   --user demo:demo
   --request POST \
   --url http://localhost:3001/articles \
   --header 'Content-Type: application/json' \
   --data '{"title":"STRING", "summary":"STRING", "description":"STRING", "createdBy":"UserId"}'

Next steps

This tutorial explained how to add one of the easiest methods to protect certain API actions from unauthorized users.

As the names mentioned, this is a very basic way to secure your API and doesn’t have any user management and control over complex flows.

In case you want to have a user management system with complex flows based on the user role or group, we recommend you take a look at how to integrate AWS Cognito using Mockless Studio.