LoopBack — Adding Authentication

Cris Ferreira Pires
1 min readApr 15, 2021
LoopBack4

This time we will be adding authentication to a simple loopback todo api.

The first part can be seen in my previous story.

First we need 2 new packages:

npm i -s @loopback/authentication @loppback/authentication-jwt

Then we need to add this on the application.ts file, so that we actually use what we just downloaded.

This function already exists so use copy the snippet into the existing one.

Also correct the DbDataSource wherever it is found to the name you used when creating your own datasource.

Now we need to create a controller for the user:

lb4 controller user

And we chose an empty controller, inside it we will handle “/login”, “/whoami” and “/signup”.

Now to make the actual controller:

Just replace everything in there (which wasn’t much to begin with) with this.

Now we actually make our api use the authentication.

We need to define it by api. So if we have multiple we need to make sure that it all of them (at least those that should) are secure.

So now on the todo controller (mind you we are continuing the last story), we will add the following:

Finally we are ready to test it.

--

--