REST api authentication for your Ionic 2 app – Part 2

Hi Friends,

Good day to you all. Hope you read the part – 1 of this series and I presume you were eagerly waiting for the second part. Well here it is.

If you hadn’t read part 1 of this series, please click here to read it as this post is a continuation of that.

Okay, lets start from where we left off. We have created the API endpoints and now let us create a front-end application using the Ionic 2 framework to consume those services.

The entire code for this Ionic 2 app can be found here.

The entire code for the backend of this app can be found here.

A screencast of this tutorial is below:

 

I will skip the installation and creation of an Ionic 2 project as I have already discussed this in my previous post here.

Once you have finished creating the application open it using your favorite editor and open the pages directory inside the app folder. Now create a new directory called userpage and create userpage.html, userpage.scss, and userpage.js files inside it respectively. Also create a directory for a signup page and do the same. Also create a authservice.js file in your homedirectory. Now your directory structure should look like this.

Kazam_screenshot_00008

Now open up the home.html file and add the below code inbetween the <ion-content> tags

We have just added two fields username and password and then a button.

Open up authservice.js and add the below code.

Now lets break it down

  1. I have injected http and navcontroller so that we could use it for making http requests and navigating to a different page.
  2. There are four methods storeUserCredentials(), loadUserCredentials(), useCredentials() and destroyUserCredentials(). These methods deal with using the token after it is received from the server.
  3. In the login method I am making a call to the REST url and passing the username and password.
  4. I am storing the response token in local storage so that it could be used in the application.
  5. The whole operation is done in a promise which is then resolved so that the async call can happen seamlessly.
  6. A similar approach is followed for signup as well.

Now open up the userpage and add the below code.

Here in this code we are just injecting the authservice so that we could call the logout function present there.

Open the userpage.html file and add the below code inbetween the <ion-content> tags.

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

Now let’s break this down.

  1. this.usercreds is hooked up with the two input fields in our login.html using ngModel.
  2. AuthService is injected here and the login method is called.
  3. The register button calls the signup page.

Open signup.js and add the below code.

This will call the register method in the authservice.js file.

Now open up signup.html and add the below code.

What we have done till now in simple terms.

  1. The user gives his username and password and the login method in the authservice is called.
  2. The login method receives the username and password and makes a POST call along with the credentials.
  3. The server receives the call and verifies it and then responds back with a token.
  4. The login method receives this token and then stores it in the local storage.
  5. The userpage is now shown to the user.

Now run the app using the below command:

(Ensure that the back-end is also running).

You will find that our app now has login/logout features and a landing page for logged in users.

Thanks for reading guys, Please share your suggestions in comments.

 

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

  • Robert Lunn

    Hi raja, I have an issue with the code, and I’m unsure how to handle it. In authservice.authenticate the promise never resolves false. If I remove the 403 status on the server side it resolves false. I’m trying to use it to display an alert if login is unsuccessful. Could you look at the code and see what the issue is? Thank you so much for your great work.

    • Uhmm, Actually, I don’t understand the problem here. If the user is not found(i.e., there is no registered user) or if there is a mismatch in the username and password then the authenticate resolves false. Else it resolves true. Did you try out with these scenarios and does it return true for that too..?

      • Robert Lunn

        I did try these different scenarios, it does not return true, I think it gives an unhandled exception error. I think relating to the .register. to test, might I reccomend, in home.js, after if(data){this.nav.setRoot(userpage);} put an else statement, to either log to console or display an alert. as a work around, I have set my server to not change the status and just send the json, however this logs it on the server as a 200, so is not ideal.

        • Yeah, Now I understand. I haven’t written code to handle those situations bro. I just wanted to provide a rough idea on how to write a frontend to handle authentication. Thanks for notifying. I will modify it and post an update when I get some time. Thanks again for reading my posts. Have a nice day.

        • Throze

          Have you solved this issue? Every tutorial I’ve seen has the same problem; the code works on a 2xx code response, but otherwise returns an unhandled exception error and just hangs.

  • Andreas Strauß

    Hi Raja, i am receiving a blanksite after starting the frontend and receiving this console log:ionic $ 0 380028 error Uncaught ReferenceError: ionic is not defined,

    • Apologies for not replying sooner sir. I hope the issue is resolved now.

  • Throze

    I’m getting an exception: [object Object] from this. It seems that the .subscribe method is simply not getting recognized for me.

    • Apologies for not replying sooner sir. I hope the issue is resolved now. If not, kindly let me know how I could be of help.

      • Throze

        It’s been resolved, thanks.

  • Anu

    my ionic v2 is using typescript rather than javascript. Really need help :(

    • Typescript is rather a superset of javascript. During compilation it is compiled into javascript and then run. So, no issues; please proceed with writing ur code in typescript.. :)

  • DC

    Hi Raja,
    Great written tutorial and video. Before I start coding can this app run in the Genymotion
    android emulator and eventually using a real device ? A mongodb windows service with
    the node server will be running on a local pc using win 8.1. The idea is to push data
    from the android phone to mongodb through a usb cable. Thanks

    • No sir, I don’t think that is possible. The db runs on localhost and since the app runs on the same I am able to connect and push/pull data. If you plan to use a real device then I would suggest you to host your db/server over the net and then use it.. Or you could simply use services like mongolab. They offer free mongodb(512 MB) hosting.

      • DC

        Great, you were able to pull/push data on a local pc using an emulator by running
        ionic run android not ionic serve. Correct ? If so, I can begin coding. We plan
        to host mongodb on an internal private server. Appreciate your comments and recommendations.

        • Uhmm.. Actually no.. I don’t use emulators much.. I either run on a device or use ionic serve. And to answer your question; I should mention that the db is connected through the nodejs server that is running and which serves the REST Api endpoints using express. The mobile app which we code simply calls the RESTful services.

          If you have hosted your node server on the net (like wordpress, twitter, reddit etc.,) and the server is able to access the db running on your private server; you could simply make a call to the rest endpoints from your app and it will run fine. There is no connectivity at any point between your mobile app and the db. You just have to see whether the server is able to connect with the db and whether the app can access the REST endpoints provided by the server.

          I apologise if I had confused you. Please let me know if you have any concerns. Thank you.

          • DC

            Raja,
            I’ll use ionic serve for my initial tests and skip the emulator step. I also have access to a Samsung Galaxy S3. When you run on a real device are you
            going through a usb connection ? If I connect to a local pc using a usb connection will I be able to push/pull data to mongodb.

          • I understand sir. Is the nodejs server running over the internet.. for eg., on a host service like Amazon aws or heroku or nodejujitsu something like that. ? If it’s simply running on a computer, you won’t be able to access via a usb cable sir, since we are making HTTP calls to the rest endpoints from our app.

          • DC

            Raja,
            I’ll use ionic serve first. Then I’ll run on a real device with a usb cable.

            I did a little research and it appears nodejs itself can be installed on a windows server, if that is the case then node server.js should work. I’m assuming the windows server has access to the internet. A simple test would be to add the whitelist plugin and observe if the files are
            downloaded. Regards

  • DAVID ALEJANDRO QUINONEZ MOSQU

    Any of you have tried to do the same in typescript ? the truth am new to this but I have a problem with providers in javascript (I’m using version 2 of ionic ) , then I thought about passing it typescript fix , but does not work either.

    • DAVID ALEJANDRO QUINONEZ MOSQU

      I just changed the definition of variables and constructor in all the .ts files (your .js files) no error. But when i try to initialize the app with ionic serve, it does not works, dont show me anything no errors no problems no buttons no inputs, anithing. Please help

  • Hector

    Hi, the front end code isnt working anymore with the lastest version of angular2, RC0, could you fix It sr ? thanks

  • Brahma chaitanya

    Hi Raj Yohan , I am very much new to this ionic2 and even fresher plz help in out in integrating googlePlus with ionic2 application for signin into our app .Dhanyawad in Advance sir