Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

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

5.00/5 (1 vote)
20 Aug 2017CPOL15 min read 24.9K   294  
MEAN Stack, Development Environment Setup, Expressjs APIs Development & Testing
In this short series of articles, I will explain the step by step application development using MEAN stack (Angular 4) with 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.

Article Series

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 and mLab 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 and DELETE 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 the ng -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 and Password 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 the ACCOUNT 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 and documents.
  • 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

  1. 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 (for MongoDB), create the User CRUD RESTful APIs through Expressjs. In client folder, we will keep Angular code that will call the Expressjs APIs and render the views in the browser.
  2. Next, open the Visual Studio Code and select File -> Open Folder.... Select the newly created mean-example folder and click on Select Folder button.
  3. You would see two empty folders, client and server in EXPLORER panel. (If Explorer is not visible, select top menu View -> Explorer).
  4. 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:
    1. 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.
    2. 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).
  5. 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.
  6. Right click on server folder select New File. Enter the file name app.js. This would be our node.js server file:

    Image 1

  7. Next, let's get the Expressjs module by npm. 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 command npm 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 and yes at the end. You would find package.json created in server folder with the basic architecture, great.
  8. 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).
  9. 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.
  10. Edit the app.js and let's add the required external modules express, path and bodyparser for now.
    JavaScript
    //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');
  11. Next, add the following code:
    JavaScript
    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);
    });
  12. 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's use 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.
  13. Right click on server folder and select Open in Command Prompt option. Enter the command node app and press Enter. You would see the Server started on port 3000 message. now open any browser, e.g., Chrome or Firefox and browse the URL http://localhost:3000. You would see I am up & running at port: 3000 message in browser. Cool, that was the quick test to check the server setup.
  14. 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:

    Image 2

  15. 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.

    Image 3

  16. 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:

    Image 4

  17. Enter the database name userdb001 and click on the bottom Continue button:

    Image 5

  18. Click on Submit Order button at the bottom:

    Image 6

  19. After few moments, you would land on the Home page with your created database available and ready to use:

    Image 7

  20. 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 database Collections, Users, Backups, etc. We will use Collections and Users tabs for now.
    1. 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 Database table. Just like Relation Database table can have multiple rows, in MongoDB one Collection can have multiple documents and of course there can be as many Collections as you need.
    2. Document: Document is just a JSON data file (Key, Value) pairs. We will see how exactly document looks like in the upcoming steps.

    Image 8

  21. Click on Add Collection button, and in the modal pop, enter the Collection name as UserInfo and click on Create button:

    Image 9

    Image 10

  22. 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.

    Image 11

  23. 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:

    Image 12

    Image 13

  24. Great! You would see that the new JSON document is created and there is an automatically assigned unique _id that is a cool feature.

    Image 14

  25. Next, let's create the database User, click on userdb001 in the previous step's screenshot on top. Click on Users tab and click on Add database user, enter the username admin and password 123456. (Or whatever you want to, but remember it). Click on Create button.

    Image 15

  26. 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.
  27. Now let's go back to node.js, we need mongojs package to connect to MongoDB from mLab 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 command npm install mongojs --save.
  28. Edit the app.js in server folder and import the newly added mongojs by adding:
    JavaScript
    var mongojs = require('mongojs');
    
  29. Next, add the following line to connect to MongoDB created in previous steps:
    JavaScript
    var db = mongojs('mongodb://admin:123456@ds149353.mlab.com:49353/userdb001', ['UserInfo']);
    
  30. 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 name routes and press Enter.
  31. Right click on newly created routes folder and select New File, enter the file name user.js and press Enter button.
  32. In newly created user.js file, add the following code:
    JavaScript
    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;
  33. 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 importing mongojs since we are using it in Get single user, Update and Delete User APIs to take the input id parameter. If you see we are using router methods get, post, put and delete, those are HTTP verbs, the first parameter in each function is the string route (you can use whatever you want), second parameter is the callback function with req, res and optional next parameter. The req parameter is the input request that would contain input parameter, body, header, etc. The res is a response from server, what is the next parameter? Try to find it yourself. In each callback function, you can see the statement var 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 copying mLab 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 from req object. Next, we are calling corresponding MongoDB functions for get, put, post and delete operations and passing the required input variable.
  34. Next edit the app.js and update it according to the following:
    JavaScript
    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);
    });
  35. We removed our test route with string message and added the bodyParser, that is middleware and provide the following information:
    1. app.use(bodyParser.json()) basically tells the system that you want JSON to be used. This would only work if header-type in our POST request would be JSON.

    2. 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)

  36. Next, we added app.use("/api",users); after importing our newly created user route file. The Expresssjs use method tells our application to use external routes (in our case, those are defined in user.js file).
  37. In app.set("userdb",db); statement, we are setting the db instance variable that is being passed with route and in user.js file, we are using request's get method in each API to use it.
  38. 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.
  39. Right click on server folder and select Open in Command Prompt. Run the command: node app and make sure you are getting the message Server started on port 3000.
  40. Once your application is up and running, open Postman and configure GET request according to the following screenshot and click on Send button:

    Image 16

  41. For POSTing new user, configure Postman according to the following screenshot (focus on red boxes), press the Send button and check the response in bottom tabs, you would see _id added in response, go to mLab documents to verify successful insertion: Image 17

  42. For PUT (update existing user), configure Postman according to the following screenshot, please remember, your id in URL would be different, so go to mLab documents to get _id for the user you want to update:

    Image 18

  43. For DELETE user, configure Postman according to following screenshot, please remember, your id in URL would be different, so go to mLab documents to get _id for the user you want to delete:

    Image 19

  44. 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.

History

  • 20th August, 2017: Created
  • 28th August, 2017: Added Part 2
  • 10th September, 2017: Added Part 3

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)