MEAN Stack with Angular 4, Auth0 Auth & JWT Authorization - Part 1





5.00/5 (1 vote)
MEAN Stack, Development Environment Setup, Expressjs APIs Development & Testing
Article Series
- Part 1: MEAN Stack, Development Environment Setup, Expressjs APIs Development & Testing
- Part 2: Angular 4 Client Development
- Part 3: Authentication & Authorization using Auth0 & JWT
Introduction
In this short series of articles, I will explain the step by step application development using MEAN stack (with Angular 4) by developing our favorite User Management application. Later on, we would add the User Authentication using Auth0 and Authorize our RESTful APIs request through JWT (JASON Web Token). We will develop our application in Visual Studio Code editor.
Background
Though this is an independent series of articles, it's better if you go through User Management article. We will be using almost the same Angular 2/4 code for User Management except creating the components, services, module, etc. through Angular CLI commands.
MEAN stands for Mongo, Expressjs, Angular and Node.js. It's also helpful if you have basic knowledge of these technologies but it is not required. I will briefly explain each technology during the development.
What We are Going to Develop and How?
We are going to download User Management (Add
/Update
/Delete
/Load
) application for here. We will download node.js, Visual Studio Code, install Angular CLI through node.js NPM, create the accounts on Auth0 for Authentication and on mLab for MongoDB creation where we will store our User information instead of SQL database.
Following is the summary of steps we are going to perform:
- Install all required software and create the
Auth0
andmLab
accounts. - Create a new project and open the project in Visual Studio Code.
- Create the Node.js server, connect to
mLab
and expose the User CRUD RESTful APIs through Expressjs. - Create required components, service and routers through Angular CLI commands according to this User Management application.
- Update the Angular client application to call Expressjs exposed RESTful APIs.
- Verify the application functionality.
- Add Login functionality, implement the
AuthGuard
to secure the User Management page route. - Add JWT implementation on both Angular Client and Expressjs Server side to secure data communication. In simple words, Angular client will send JASON Web Token (some kind of hashed string by hashing algorithm) with
GET
,POST
,PUT
andDELETE
request that would be verified on Server side by Expressjs to make sure it is not accessible to an unauthorized user. - At last, we would see Testing through Karma, Jasmine, learn about build like AOT. (Optional)
Still interested?
Setup the Development Environment
- Download the Visual Studio Code and install it if you don't have it already.
- Download the Node.js and install it if you don't have the latest version. Once the installation is completed, open the command prompt and run the
node -v
command to verify the successful installation and get the node version. - Open the command prompt and install the Angular CLI by
npm install -g @angular/cli
command. Once the installation is completed, run theng -v
command to check the successful installation and get the Angular CLI version. - Go to https://auth0.com/ website, click on SIGN UP button on the right corner. Enter the
Email
andPassword
or sign up with Github, Google or Microsoft account. It's up to you. Once you would sign up, it would ask you to enter theACCOUNT NAME
, enter any unique name and click on Next button at bottom. Enter self-explanatory information on the next page and click on Create Account button. You would receive the verification email to the email address you used to sign up. Click on Verify Your Account button or link in the email, login with your credential, you would be redirected to the page with successful verification and 21 days trial period information. That's all for now, leave it here, we will come back to it later. - Go to https://mlab.com/ website, click on SIGN UP button on the right corner. Enter the new account information and click on Create Account button. You would receive the verification email to the email address you used to sign up. Click on Verify Your Account link in the email, login with your credential, you would be redirected to the page with successful verification. Leave it here, we will come back later to create the
collection
anddocuments
. - That's all for environment setup, we will add the required client packages for Angular and node.js in the application through npm (Node Package Manager).
Let's Start
- Create the project folder mean-example and create two folders, server and client inside in it anywhere in your computer or where you keep your projects. In server folder, we will create a node.js application, connect it to
mLab
website (forMongoDB
), create the User CRUD RESTful APIs throughExpressjs
. In client folder, we will keep Angular code that will call the Expressjs APIs and render the views in the browser. - Next, open the Visual Studio Code and select File -> Open Folder.... Select the newly created mean-example folder and click on Select Folder button.
- You would see two empty folders, client and server in EXPLORER panel. (If Explorer is not visible, select top menu View -> Explorer).
- First, let's create the server side application. As discussed earlier, we will develop the server side application in node.js and Expressjs but before going to development, let's understand node.js and Expressjs:
- Node.js: You would find plenty of fancy definitions online but just in simple words, it is a server side framework for application and websites written in JavaScript, fast and non-blocking, How? Just for understanding, when it performs any task, it doesn't stay there and wait for its completion, instead, it registers the callback function to it and moves to the next task, when the previous task is completed, it calls the callback function to notify its completion and so on. That makes the node.js event driven, like event will be fired once (when Node is ready to call the callback) and the callback acts as the event handler. Now node.js itself has thin functionalities, that's why we have lot of libraries/modules we can import in node.js application to perform our required functionality. One of them is Expressjs.
- Expressjs: A node.js framework for web application, RESTful APIs and you can also define routes in it. Expressjs is flexible to have any template framework (the HTML or View file) e.g., Jade, Pug or EJS. Since we are using Angular 4 as a client side and not creating any template/view on server side. So don't worry about any template framework for now. We will only use EJS to render our HTML. Our Expressjs would point to dist folder that would be generated once we will build our Angular4 client with Angular CLI
build
command (We will briefly look into it later).
- Though you can use Express Application Generator CLI to generate the Express server, pug views, routes, folder, etc. But I would create the required files manually because I only need fewer files. You can go ahead and play with Express CLI on your own.
- Right click on server folder select New File. Enter the file name app.js. This would be our node.js server file:
- Next, let's get the
Expressjs
module bynpm
. I will keep the server and client package.json file separately. Right click on server folder in EXPLORER panel and select Open in Command Prompt. First thing we will create the package.json file in server folder. Enter the commandnpm init
in command prompt and press Enter, it will ask you for a little information, e.g., Application name, author, description, etc. Add it here or just keep pressing Enter andyes
at the end. You would find package.json created in server folder with the basic architecture, great. - Enter the following command to install the Expressjs:
npm install express --save
. Check the package.json file, under dependencies section, you would find "express": "^4.15.4" (or any updated version). - Next run the
npm install body-parser --save
&npm install ejs --save
commands in command prompt. We already have talked about the EJS, the JavaScript template you can use with Expressjs to render the view. - Edit the app.js and let's add the required external modules
express
,path
andbodyparser
for now.//Expressjs module, require is node.js syntax to import the module. var express = require('express'); //For file path, we will use it to point the Angular dist folder. var path = require('path'); //body-parser extracts the entire body portion of an incoming //request stream and exposes it on req.body. var bodyParser = require('body-parser');
- Next, add the following code:
var port = 3000; var app = express(); app.use('/', function(req, res){ res.send("I am up & running at port: "+ port); }); app.listen(port, function(){ console.log('Server started on port '+port); });
- The above code is quite self-explanatory, we are specifying the application port, we are creating the expressjs instance. In the next statement, we are specifying if there is any localhost URL specified without any route, just send the text "
I am up & running at port: 3000
" to the browser. The Express'suse
method allows our application to use external routes as part of the application.app.listen
will open/use the specified port (3000) for localhost. Make sure this port is not already been used by any other process. You can specify any available port. - Right click on server folder and select Open in Command Prompt option. Enter the command
node app
and press Enter. You would see theServer started on port 3000
message. now open any browser, e.g., Chrome or Firefox and browse the URL http://localhost:3000. You would seeI am up & running at port: 3000
message in browser. Cool, that was the quick test to check the server setup. -
Next step is to setup
User
database in MongoDB and expose the RESTful CRUD APIs in Expressjs. Open the https://mlab.com website, login with the credentials created in previous steps. After login, you would land to the following page: -
On top of
MongoDB Deployment section
, click on Create New button, in the next screen, select Plan Type SANDOX. Once you will click on SANDOX, Continue button would appear at the bottom, click on it. -
Since this free database would be created on AWS, the next screen will ask you to select the AWS region, select your nearest/desired region. I am in Virginia so I will select US East (Virginia), click the Continue button at the bottom after selecting the Region:
-
Enter the database name
userdb001
and click on the bottom Continue button: -
Click on Submit Order button at the bottom:
-
After few moments, you would land on the Home page with your created database available and ready to use:
- In the above screenshot, click on newly created row starting with
ds149353...
you would land on the following screens. This page has important information, e.g., MongoDB URI, through which we will connect to MongoDB from node.js. Other information is about databaseCollections
,Users
,Backups
, etc. We will use Collections and Users tabs for now.- Collections: You can get MongoDB Collections definition online but since I am not a big fan of definitions. Just for understanding, consider
Collection
as a Relational Databasetable
. Just like Relation Databasetable
can have multiple rows, in MongoDB oneCollection
can have multipledocuments
and of course there can be as manyCollections
as you need. - Document:
Document
is just a JSON data file (Key, Value) pairs. We will see how exactlydocument
looks like in the upcoming steps.
- Collections: You can get MongoDB Collections definition online but since I am not a big fan of definitions. Just for understanding, consider
-
Click on Add Collection button, and in the modal pop, enter the Collection name as
UserInfo
and click on Create button: -
Cool, let's create one sample document, click on
UserInfo
collection (the red area). You would land on the following screen. Click on Add document button. -
You would land on the following editor, now Add the JSON data according to the second screenshot into Create Document editor and click on Create and go back:
-
Great! You would see that the new JSON
document
is created and there is an automatically assigned unique_id
that is a cool feature. -
Next, let's create the database
User
, click onuserdb001
in the previous step's screenshot on top. Click on Users tab and click on Add database user, enter the usernameadmin
and password123456
. (Or whatever you want to, but remember it). Click on Create button. - That's all we need to do on
mLab
website, note down the To connect using a driver via the standard MongoDB URI value. It would be different for you guys. We need it to connect MongoDB from node.js. - Now let's go back to node.js, we need
mongojs
package to connect to MongoDB frommLab
website. Repeat the same steps, if your command prompt is not already open, right click on server folder and select Open in Command Prompt, enter the commandnpm install mongojs --save
. - Edit the app.js in server folder and import the newly added
mongojs
by adding:var mongojs = require('mongojs');
- Next, add the following line to connect to MongoDB created in previous steps:
var db = mongojs('mongodb://admin:123456@ds149353.mlab.com:49353/userdb001', ['UserInfo']);
- Now, we will create
routes
for User CRUD APIs, let's create it in a separate folder. Right click on server folder and select New Folder, enter the nameroutes
and press Enter. - Right click on newly created routes folder and select New File, enter the file name user.js and press Enter button.
- In newly created user.js file, add the following code:
var express = require('express'); var router = express.Router(); var mongojs = require('mongojs'); //Get All Users router.get('/users', function(req, res){ var db = req.app.get("userdb"); db.UserInfo.find(function(err, users){ if(err){ res.send(err); } res.json(users); }); }); // Get Single User router.get('/user/:id', function(req, res, next){ var db = req.app.get("userdb"); db.UserInfo.findOne ({_id: mongojs.ObjectId(req.params.id)}, function(err, task){ if(err){ res.send(err); } res.json(task); }); }); //Save User router.post('/user', function(req, res){ var db = req.app.get("userdb"); var user = req.body; db.UserInfo.save(user, function(err, user){ if(err){ res.send(err); } res.json(user); }) }); // Update User router.put('/user/:id', function(req, res, next){ var db = req.app.get("userdb"); var user = req.body; db.UserInfo.update({_id: mongojs.ObjectId(req.params.id)}, user, {}, function(err, user){ if(err){ res.send(err); } res.json(user); }); }); // Delete User router.delete('/user/:id', function(req, res, next){ var db = req.app.get("userdb"); db.UserInfo.remove({_id: mongojs.ObjectId(req.params.id)}, function(err, user){ if(err){ res.send(err); } res.json(user); }); }); module.exports = router;
- Let's briefly understand what we are doing in user.js. First, we are importing Expressjs to use
router
for very obvious reason, to use API's routes. Next, we are importingmongojs
since we are using it in Get single user, Update and Delete User APIs to take the inputid
parameter. If you see we are using router methodsget
,post
,put
anddelete
, those are HTTP verbs, the first parameter in each function is thestring
route
(you can use whatever you want), second parameter is the callback function withreq
,res
and optionalnext
parameter. Thereq
parameter is the input request that would contain input parameter, body, header, etc. Theres
is a response from server, what is thenext
parameter? Try to find it yourself. In each callback function, you can see the statementvar db = req.app.get("userdb");
that is our MongoDB instance we are creating it in app.js. I only added this statement to show you how you can send the data/parameter from app.js to user.js or any other route. Instead of creating the MongoDB instance in each route and copyingmLab
connection string everywhere (in case you have more APIs routes), I am just keeping it in app.js file and exposing it as a parameter so that each route can use it fromreq
object. Next, we are calling corresponding MongoDB functions forget
,put
,post
anddelete
operations and passing the required input variable. - Next edit the app.js and update it according to the following:
var express = require('express'); var path = require('path'); var bodyParser = require('body-parser'); var users = require('./routes/user'); var mongojs = require('mongojs'); var db = mongojs('mongodb://admin:123456@ds149353.mlab.com:49353/userdb001', ['UserInfo']); var port = 3000; var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.set("userdb",db); app.use("/api",users); app.listen(port, function(){ console.log('Server started on port '+port); });
- We removed our test route with
string
message and added thebodyParser
, that is middleware and provide the following information:-
app.use(bodyParser.json())
basically tells the system that you want JSON to be used. This would only work ifheader-type
in ourPOST
request would be JSON. -
bodyParser.urlencoded({extended: ...})
basically tells the system whether you want to use a simple algorithm for shallow parsing (i.e.,false
) or complex algorithm for deep parsing that can deal with nested objects (i.e.,true
). (Stackoverflow ref)
-
- Next, we added
app.use("/api",users);
after importing our newly createduser
route file. The Expresssjsuse
method tells our application to use external routes (in our case, those are defined in user.js file). - In
app.set("userdb",db);
statement, we are setting thedb
instance variable that is being passed with route and in user.js file, we are using request'sget
method in each API to use it. - So far, we have created the User Management APIs, let's test it in Postman. Postman is a very easy tool to test APIs, you can use SOAP UI or Fiddler too. Download and install Postman according to your operating system.
- Right click on server folder and select Open in Command Prompt. Run the command:
node app
and make sure you are getting the messageServer started on port 3000
. -
Once your application is up and running, open Postman and configure
GET
request according to the following screenshot and click on Send button: -
For
POST
ing new user, configure Postman according to the following screenshot (focus on red boxes), press the Send button and check theresponse
in bottom tabs, you would see_id
added in response, go tomLab
documents
to verify successful insertion: -
For
PUT
(update existing user), configure Postman according to the following screenshot, please remember, yourid
in URL would be different, so go tomLab
documents to get_id
for the user you want to update: -
For
DELETE
user, configure Postman according to following screenshot, please remember, yourid
in URL would be different, so go tomLab
documents to get_id
for the user you want to delete: - That's all for this article, you can do the practice, expose more User APIs, update the routes, create MongoDB
documents
with different information till you read the next part. :)
In the Next Part
In this article, we got a basic understanding of node.js and Expressjs. We also setup our development environment and created accounts on mLab for MongoDB and Auth0 for authentication and JWT. At the end, we exposed the User Management APIs through Expressjs and tested them in Postman.
In the next part, we will create the Angular 4 client application, integrate it with node.js and will call the User Management APIs to load, add, update and delete the user.