Develop an Authentication API using AdonisJs 4 + MongoDB
This tutorial will show how to develop a simple Authentication REST API using AdonisJs and MongoDB.
Software Installation
- MongoDB Community https://www.mongodb.com/try/download/community
- Postman https://www.postman.com/downloads/
- Node.js https://nodejs.org
- AdonisJS: install from the following command:
npm i -g @adonisjs/cli
Add User in MongoDB
Only for Windows, set Environment Variable > Path
Start mongo shell with this command:
mongo --host localhost --port 27017
Add new user with these two commands:
use admindb.createUser({user: "myUserAdmin", pwd: "myUserAdmin", roles: [{role: "userAdminAnyDatabase", db: "admin"}, "readWriteAnyDatabase"]})
Verify is the user is added:
db.getUsers()
Create AdonisJS project
Use this command:
adonis new adonis-mongodb-server
Start server:
cd adonis-mongodb-serveradonis serve --dev
Test on your browser with http://127.0.0.1:3333/
AdonisJS + MongoDB
Add lucid-mongo module into our project:
npm i --save lucid-mongo
Edit start/app.js
Edit .env
Edit config/database.js
Edit config/cors.js
Edit config/shield.js
API for User Register
Add User Controller:
adonis make:controller User --type http
Edit app/Controllers/Http/UserController.js to have register method for handling POST request.
Edit start/routes.js to add a route for register POST request to be handled by register method in User Controller.
Use Postman to test the API for User Register
{
"email": "karnyong@gmail.com",
"password": "1234",
"fname": "Karn",
"lname": "Yong"
}
Verify that the user data is stored in MongoDB by using MongoDB Compass.
In mydb database, select users collection:
A user data is there!
API for User Login
Edit app/Controllers/Http/UserController.js
Edit config/auth.js, we are going to use Json Web Tokens (JWT) to securely transmitting information between two parties (for ex. client and server) in the form of json object.
Edit start/routes.js
Use Postman to test the API for User Login
Use Postman to test the API for User List (Use token from the login).
More explanation about JWT:
The full source code can be found here:
Extra
Develop a simple mobile app with react native to use this authentication API
expo init login-react-native
cd login-react-native
yarn add native-base --save
yarn add @react-navigation/native --save
yarn add @react-navigation/stack --save
yarn add react-native-gesture-handler --save
yarn add react-native-screens --save
yarn start
Download or create your own logo. You can do it from here, for example:
https://www.freelogodesign.org/
Rename your logo file to logo.png and put it in assets folder.
Edit App.js
Create Login.js (Change the IP address on line 16 to be your IP address)
Create Profile.js
Result:
Article by Karn Yongsiriwit, Ph.D.
College of Digital Innovation Technology, Rangsit University