Rest api authentication for your Ionic 2 app – Part 3

Hi Friends,

Hope you’re all fine. Here I am, back with another tutorial, the last one of the three part series in authentication for Ionic 2 apps. I hope you have read both Part 1 and Part 2 of this series so that you would understand this one.

The complete code of this app can be found here.

The backend of this tutorial series can be found here.

A screencast of this tutorial:

Without further ado let’s get started from where we left off. Now in Part 2 we saw how to login and how the token returned is stored in our localstorage. In this part we will see how to make authorized requests using that token.

To make authorized requests we need a API endpoint to call on right ? So far we have created end points in our backend for registering a new user and authenticating that user. Lets open up our backend.

In the actions file add a new method called getinfo as shown below:

This method will accept incoming requests and split the headers, thereby extracting the token from a header and it will decode it using our config.secret. If the decode is successful, then it returns a hello message with the user’s name. (If decode is not successful it will return a 500 signature verification failed).

Now add the below line to your routes.js file in the routes directory.

That’s it. We are all set with the backend.

Now opening up our Ionic app.

Open up userpage.js and add the below code.

This method just calls the getinfo method in the authservice and if its’ a success displays an alert showing the user’s name.

Wire this up to the html file with a button.

Now open up authservice.js file and add the below code.

This will get the token from our localstorage and place in the Authorization header of our request. Upon successful call the returned data will be sent (as a promise) to the userpage.js file.

That’s it guys, this is how you make an authorized request to the back-end server to perform tasks.

Hope you enjoyed reading the series. Please comment your suggestions if any. Thanks.

Liked it? Take a second to support admin on Patreon!
  • DC

    Hi,
    I’m unable to complete part 1 because I think there is a missing file.

    var Session = require(‘../models/session’); – the models folder is missing session.js
    Can you update the github repo to include this file ?
    Thanks