Click here to Skip to main content
14,216,889 members
Click here to Skip to main content
Article
Posted 20 Aug 2017

Stats

16.6K views
234 downloads
18 bookmarked

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

,
Rate this:
5.00 (1 vote)
Please Sign up or sign in to vote.
5.00 (1 vote)
20 Aug 2017     CPOL    
In this short series of article, I would 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. 

Content

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 article, I would 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 but its better if you go through User Management article. We will be using almost 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 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 new project and open it 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, Jasime, 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 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 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 it 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 it completion and so on. That's make 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 a 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 play with Express CLI 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:

  1. 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 few 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.  
  2. 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).
  3. 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.
  4. Edit the app.js and let's add required external modules express, path and bodyparser 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 extract the entire body portion of an incoming 
    //request stream and exposes it on req.body.
    var bodyParser = require('body-parser');
  5. 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);
    });
  6. The above code is quite self-explanatory, we are specifying the application port, we are creating the expressjs instance. In 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. 
  7. 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.
  8. 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: 

  9. On top MongoDB Deployment section, click on Create new button, in next screen select Plan Type SANDOX. Once you will click on SANDOX, Continue button would be appeared at the bottom, click on it.

  10. 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 bottom after selecting the Region:

  11. Enter the database name userdb001 and click at the bottom Continue button:

  12. Click on Submit Order button at bottom: 

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

  14. In above screenshot, click on newly created row starting with ds149353...you would land to 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 upcoming steps. 
  15. click on Add Collection button, and in the modal pop enter the Collection name as UserInfo and click on Create button:

  16. Cool, let's create one sample document, click on UserInfo collection (the red area). You would land to following screen. Click on Add document button.

  17. You would land to following editor, now Add the JSON data according to the second screenshot into Create Document editor and click on Create and go back:

  18. Great, you would see that the new JSON document is created and there is a automatically assigned unique _id that is a cool feature. 

  19. Next, let's create the database User, click on userdb001 in 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.

  20. 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.
  21. Now let's go back to node.js, we need mongojs package to connect to MongoDB from mLab website. Repeat the same steps, if you command prompt is not already open, right click on server folder and select Open in Command Prompt, enter the command npm install mongojs --save.
  22. Edit the app.js in server folder and import the newly added mongojs by adding:
    var mongojs = require('mongojs');
    
  23. Next, add following line to connect to MongoDB created in previous steps: 
    var db = mongojs('mongodb://admin:123456@ds149353.mlab.com:49353/userdb001', ['UserInfo']);
    
  24. 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.
  25. Right click on newly created routes folder and select New File, enter the file name user.js and press enter button.
  26. In newly created user.js file, add 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;
  27. 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.
  28. Next edit the app.js and update it according to 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);
    });
  29. We removed our test route with string message and added the bodyParser, that is middleware and provide 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)

  30. 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).
  31. 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.
  32. 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.
  33. 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.
  34. Once your application is up and running, open the Postman and configure GET request according to the following screenshot and click on Send button:

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

  36. For PUT (update existing 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 update:

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

  38. 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 then I write next part :)

In Next Part

In this article, we got 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 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

Created: 8/20/2017

Added Part 2: 8/28/2017

 

License

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

Share

About the Author

Yaseer Mumtaz
Software Developer (Senior)
United States United States
A senior software engineer with more than thirteen years of experience in application development. I mostly work in .NET, Angular, MEAN stack technologies and love to share what I do and learn during my day to day job. Please check my tutorials and blog:
https://fullstackhub.io
https://fullstackhubblog.com

Comments and Discussions

 
-- There are no messages in this forum --