Tutorial: create api with authentication using loopback IBM

Pedro Antunes
Nerd For Tech
Published in
3 min readApr 18, 2021

--

The first step is to duplicate our previous project or create a new one y can acess it my previous tutorial here.

Lets begin with opening Noddejs command prompt an type the following commands:

lb4 example todo

cd loopback4-example-todo

And install the authentication extension:

npm i --save @loopback/authentication @loopback/authentication-jwt

After the instalation is complete go to the root folder of our project and open the src folder and the open as well the application.ts file with notepad++.

Pay atention on this step, the file must have the following code, adapt it so it culd look like this:

The next step is to create a controller , to do it go to nodejs prompt and type the command:

lb4 controller

The name of the controller is:

User

And then choose the option:

Empty Controller

The next step is to add endpoints to the UserController.

Go to the root folder of our project and open the src folder, the controllers folder and open the file user.controller.ts and edit it to look like this:

The next step is to protect our api to do it open the src folder and the controllers folder and edit the todo.controller.ts to look like this:

Finnaly go and test our API:

on the nodejs prompt type:

npm start

And the go to:

http://localhost:3000/explorer.

And the output of our user Controller shoud look like this:

To test the POST/signup use this and check if it works:

{
"email": "testuser2@abc.com",
"password": "testuser2"
}

To test our POST/users/login copy the follow token and go to the top of the API Explorer, click the “Authorize” button.

{
"token": "aaaaaaaaa.aaaaaaaaaaaaaaaaa"
}

Paste the token that you previously copied to the “Value” field and then click Authorize.

--

--