REST api authentication for your Angular2 / Ionic 2 app – Part 1

Hi Friends,

Good day to you guys. Hope you are all well. I would like to thank everyone who has been reading my blog and checking it to see for new posts everyday. Thank you guys, your support has encouraged me to write more posts and help out more friends in need.

So, lets get started with authentication. Authentication in simple terms is nothing but providing & restricting access of different aspects in the application to users. In this tutorial I will show you how to build an authentication system for your Ionic 2 applications. The below diagram shows how our app is going to be based.


This tutorial follows the above block diagram and I will show you how to write code for everything mentioned in the diagram.

We are going to use:

  • Ionic 2 (For the mobile app).
  • NodeJS and ExpressJS for writing the server. (Wiring up the API endpoints).
  • MongoDB for database. (We will use mongoose to play with the db).

Basically its a MEAN app where we use Ionic 2 framework to wire up the front-end.

For the sake of simplicity I have divided this tutorial into 3 parts.

The first part will show how to build the back-end. i.e., The database, Creation of REST Api endpoints.

The second part will show how to build a mobile app to consume these services.

(If you are writing a web app and using Angular 2 please click here )

The third part will show how send authorized requests from the mobile app and how to verify the authenticity of the requests on the server side.

The code for the tutorial is available here.

And as always, the screencast for this tutorial is below:

Lets begin.

First of all create the app (possibly in a new directory. Just use npm init). Then create a server.js file. Now run the below command in a console to install dependencies.

Then open the server.js file and add the below code in it.

Its pretty straightforward. We create our app using express and then we connect to a mongodb instance using mongoose. Then we start our server on port 3333. You are probably wondering about config.database and where it comes from. Lets create that file.

Create a directory called config and create a file called database.js in it. Then add the below code.

Now our next step would be to create a model file. Lets call that user. Create a directory called model and create a file user.js in it and then add the below code.

Please install bcrypt using – npm install bcrypt.

The UserSchema here will contain two fields, name and password. I have already made a post about the how to use bcrypt to encrypt your passwords before in a previous post here.

Now we need to write a function that will check the username and password which we receive in our request against the existing data in the db and we also need to create a REST Api endpoint.

Now before we do that; lets do one another interesting thing. As I mentioned earlier we are going to use tokens for this entire authentication system. So, lets work on token generation. We will be using a npm module called passport for this task.

Please install passport, passport-jwt and jwt-simple modules.

Now inside the config folder create a file called passport.js and add the below code.

This is nothing but creating a JWTStrategy which will sign our tokens with the secret value which we added in our database file in the config folder.

Now to use this in our app add the below lines in the server.js file.

Okay now let us create the method to actually do the authentication process.

Create a folder named actions and create the methods.js file in it. Then add the below code.

Now this authenticate function would simply get the username, password from the request (made by the device) and then check the db for the user. if found it compares the password and then encodes the user object into a json web token which is sent in the response.

We need to wire this up with a api endpoint now.

Create a folder called routes and inside it create a file called routes.js. Then add the below code in it.

Now we have a REST Api which will authenticate a given user and return a json web token if he is a valid user.

Before we begin testing we need to add body-parser module to our application. Install it using npm install body-parser. Then add the below code in server.js file.

Now simply add a user to our db using the command

Start your app using – node server.js

Now open up postman or your rest api testing tool and then make a POST request to this url with the parameters as name and password. If everything works well you will see a token as your response as shown below in the screenshot.



This is Part 1 – Building the REST endpoint for our app. In Part 2 and Part 3 I will show you how to make an Ionic 2 app and then consume the Api we created here and how authentication is actually done.

Thanks for reading guys. Peace. :)

Liked it? Take a second to support admin on Patreon!
  • Pingback: Rest api authentication for your Ionic 2 app – part 3 | T-Pub :)()

  • Pingback: REST api authentication for your Ionic 2 app – Part 2 | T-Pub :)()

  • Sander

    hi! thanks for sharing this. I want to use this together with the angular2 authentication.

    how to ‘install’ this?

    i get an error message
    process.nextTick(function() { throw err; })
    Error: connect ECONNREFUSED
    at Object.exports._errnoException (util.js:860:11)
    at exports._exceptionWithHostPort (util.js:883:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)

    Can you suggest something here?
    i am blank ; )

    • Could you please check whether your db is up and running.. (MongoDB).. ?

      • Sander

        oh oh, how do i do this?

        (quick reply +10!)

      • Sander

        oke got it.
        needed to install mongodb
        (then first update homebrew again)
        installed it all, run it
        then your script worked


      • Sander

        oke, next step:
        mongodb is running
        backend server is running
        when i go to url: http://localhost:3333/authenticate
        i get: Cannot GET /authenticate
        (403 forbidden)

        any suggestions?

        • yeah, before trying to authenticate, we need to get a few users into the db.. send a post request to the url http://localhost:3333/adduser with the name and password as parameters. Then using those parameters try to authenticate.

          • Sander

            oke i approached it in another way
            I just used the network server here at location for auhtentication.
            and it worked!
            got the token back

            thanks buddy for the help

  • DC

    I followed the steps to build the server.js file. When I start the node server, I get an error
    cannot find module ‘../model/session. Here’s a code snippet from above :

    var Session = require(‘../models/session’);Should the folder be model or models ? The source shows a model folder.
    Also, I checked the source files and did not see a session.js. Thanks

  • Moiz Kachwala

    Check this out: Angular2 express and mongoose combination:

  • Nawel Choura

    please tell me what changes do i have to make if i’m using mysql database as a backand for my ionic 2 app

  • mohan

    hi,thanks for sharing this.please explain how to run this code to postman.i get error from postman ‘Authentication failed, User not found’

  • Josimar Reis

    Great article.

  • Sanchit Mahajan

    How to write getinfo() using laravel passport… thanks…

  • Kieran Rippy Thompson

    I’m getting cannot get /adduser 404 response :/