Ionic 3 and Angular 4: PHP Restful API User Authentication for Login and Signup.
Wall Script
MailxEngine
Follow Me:
Thursday, June 22, 2017

Ionic 3 and Angular 4: PHP Restful API User Authentication for Login and Signup.

Here is the continued article on my previous post for creating a welcome page with login and logout. Today’s post explains how to implement login authentication system for your AngularJS applications. It will show you how to log in with a user and store the user session, so it deals with token based authentication. Since we are using token based authentication, it protects if any unauthorized request is made and notices for a new login if required. This makes your application’s authentication to be more secured compared with any other authentication system. Every user details will be stored in an external database and a PHP based API is used in the backend for handling this authentication. Hope you’ll find it more easily using this as your authentication system in your AngularJS projects. Let’s look into the live demo and follow the below code.

Ionic 3 and Angular 4:Login and Signup with PHP Restful API.


Live Demo


Video Tutorial
Ionic 3 and Angular 4: PHP Token Based Restful API User Authentication Login and Signup.


Database Design
To build the user feed system, you have to create two tables such as Users and Feed. You can check my previous tutorials for creating token-based API system.

Users
User table contains all the users registration details.
CREATE TABLE users(
user_id int AUTO_INCREMENT PRIMARY KEY,
username varchar(50),
password varchar(300),
name varchar(200),
email varchar(300));

Feed
This table contains user daily updates.
CREATE TABLE feed(
feed_id int PRIMARY KEY AUTO_INCREMENT,
feed text,
user_id_fk int
);

Download PHP Restul Project
$git clone https://github.com/srinivastamada/PHP-Slim-Restful.git


Create an Authenstication Service Provider
You have to create an injectable component for API autentication. The following ionic command help you to create files automatically.
$ionic g provider authService

app.module.ts
Now go to src/app/app.module.ts and import authService provider and HttpModule.
Now got src/app/app.module.ts and import Welcome, Login and Signup pages.
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { MyApp } from './app.component';
import { AuthService } from '../providers/auth-service';
import { Welcome } from '../pages/welcome/welcome';
import { Login } from '../pages/login/login';
import { Signup } from '../pages/signup/signup';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    Welcome,
    Login,
    Signup,
    TabsPage
  ],
  imports: [
    BrowserModule, HttpModule
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    Welcome,
    Login,
    Signup,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen, AuthService,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

authService.ts
Include post data function for HTTP post access. You will understand more in the youtube video.
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';

let apiUrl = 'http://yourdomain.com/PHP-Slim-Restful/api/';

@Injectable()
export class AuthService {

  constructor(public http : Http) {
    console.log('Hello AuthService Provider');
  }

  postData(credentials, type) {
    return new Promise((resolve, reject) => {
      let headers = new Headers();

      this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers})
        .subscribe(res => {
          resolve(res.json());
        }, (err) => {
          reject(err);
        });
    });

  }

}

signup.ts
Here you have to import AuthService provider and implement with user signup data. Once the API call is succesful, the user data storing into application local storage with accessing data key call userData.
import { Component } from '@angular/core';
import {  NavController} from 'ionic-angular';
import { TabsPage } from '../tabs/tabs';
import { LoginPage } from '../login/login';
import { AuthService } from '../../providers/auth-service';

@Component({
  selector: 'page-signup',
  templateUrl: 'signup.html',
})
export class SignupPage {
  responseData : any;
  userData = {"username": "","password": "", "name": "","email": ""};

  constructor(public navCtrl: NavController, public authService:AuthService ) {
  }

  signup(){
     this.authService.postData(this.userData,'signup').then((result) => {
      this.responseData = result;
      if(this.responseData.userData){
      console.log(this.responseData);
      localStorage.setItem('userData', JSON.stringify(this.responseData));
      this.navCtrl.push(TabsPage);
      }
      else{ console.log("User already exists"); }
    }, (err) => {
      // Error log
    });

  }

  login(){
    //Login page link
    this.navCtrl.push(LoginPage);
  }
}

signup.html
Bind the userDetails object with form inputs.
<ion-content padding class="appBackground">
  <ion-card>
    <ion-card-header>
      Registration
    </ion-card-header>
    <ion-card-content>
      <ion-list>
        <ion-item>
          <ion-label stacked>Name</ion-label>
          <ion-input type="text" [(ngModel)]="userData.name"></ion-input>
        </ion-item>

        <ion-item>
          <ion-label stacked>Email</ion-label>
          <ion-input type="text" [(ngModel)]="userData.email"></ion-input>
        </ion-item>

        <ion-item>
          <ion-label stacked>Username</ion-label>
          <ion-input type="text" [(ngModel)]="userData.username"></ion-input>
        </ion-item>

        <ion-item>
          <ion-label stacked>Password</ion-label>
          <ion-input type="password" [(ngModel)]="userData.password"></ion-input>
        </ion-item>

        <button ion-button full color="success" (click)="signup()">Sign up</button>
        <a href="#" (click)="login()">Login Page</a>
      </ion-list>
    </ion-card-content>
  </ion-card>
</ion-content>

login.ts
You have to follow the same like signup module.

home.ts
Reading the application local storage data and binding with userDetails. Logout function is clearing the local storage data and redirecting to the welcome page with time deplay option.
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  userDetails : any;
  responseData: any;

  userPostData = {"user_id":"","token":""};

  constructor(public navCtrl: NavController, public authService:AuthService) {
  const data = JSON.parse(localStorage.getItem('userData'));
  this.userDetails = data.userData;

  this.userPostData.user_idthis.userDetails.user_id;
  this.userPostData.tokenthis.userDetails.token;

}

backToWelcome(){
   const root = this.app.getRootNav();
   root.popToRoot();
}

logout(){
     localStorage.clear();
     setTimeout(() => this.backToWelcome(), 1000);
}

}

home.html
Binding the local storage data with HTML template.
<ion-header>
  <ion-navbar>
    <img ion-right src="assets/imgs/bananalogo.png" class="navbarLogo" />
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Welcome to {{userDetails.name}}</h2>
  <h3>Email: {{userDetails.email}}</h3>
  <button ion-button color="primary" (click)="logout()">Logout</button>
</ion-content>

Build iOS App
Following commands for executing Xcode build, watch the video tutorial you will understand more.
$ cordova platform add ios
$ ionic build ios

Build Android App
Open Android build using Android SDK>
cordova platform add android
ionic build android

Previous Video Tutorial
Ionic 3 and Angular 4 Create a Welcome Page with Login and Logout.



Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


74 comments:

  1. could you just make upload Ionic 3 and Angular 4 json parsing Example and Push Notification pls.
    Thanks
    -Sapan

    ReplyDelete
  2. This is video too much helpfull and work for me
    Thanks
    -sapan

    ReplyDelete
  3. your tutorials helping to me lot, thanks

    ReplyDelete
  4. why there is not error message if i use random account

    ReplyDelete
  5. Error: this.userDetails is undefined

    ReplyDelete
    Replies
    1. Clear your browser local storage. Go to developer tools -> application -> Clear Site Data

      Delete
    2. Thank you so much. Ok After log in, user can insert some details to other table How can we do ... can you please help me ? like want to insert feed data from ionic.

      Delete
    3. Hi Srinivas, some how I've done inserting data from ionic.
      One thing I want to know how to display toast msg when same user signup like "user already existed" ?

      Delete
  6. {"error":{"text":"Enter valid data"}}

    ReplyDelete
  7. am also getting this error {"error":{"text":"Enter valid data"} please help.!

    ReplyDelete
  8. The video is very helpful. Thanks for the share

    ReplyDelete
  9. Help!!
    XMLHttpRequest cannot load http://192.168.1.10/slimrest/index.php/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

    ReplyDelete
    Replies
    1. I was error too, u did edit it ? Can u help me?

      Delete

    2. if (isset($_SERVER['HTTP_ORIGIN'])) {
      header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
      header('Access-Control-Allow-Credentials: true');
      header('Access-Control-Max-Age: 86400'); // cache for 1 day
      }

      // Access-Control headers are received during OPTIONS requests
      if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
      header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
      header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

      exit(0);

      Add these lines to the php file on top

      Delete
  10. ERROR DOMException [NetworkError: "A network error occurred."
    code: 19
    nsresult: 0x80530013
    location: http://localhost:8100/build/polyfills.js:3]

    ReplyDelete
  11. Have an example of registration With SMS code using Restfull API??

    ReplyDelete
  12. i got this error:

    Property 'app' does not exist on type 'HomePage'

    please help

    ReplyDelete
    Replies
    1. import { App, NavController } from 'ionic-angular';

      constructor(public navCtrl: NavController, public appCtrl: App, public authService:AuthService)

      const root = this.appCtrl.getRootNav();

      Delete
  13. {error: {…}}error: text: "Enter valid data" iam getting error while signup

    ReplyDelete
    Replies
    1. Do you fix it? i am getting the same error!!

      Delete
  14. hi, when i'm submitting the form using yours api module, then we get an error of "XMLHttpRequest cannot load http://mywebsite.com/Home/Login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access."

    my api is build in .net , so can you help me, coz im new to ionic

    ReplyDelete
    Replies
    1. hi
      if you install this plugin, your problem solved
      https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related

      Delete
  15. hi , im new to ionic so i'll see your video, then apply same on my project, but when we run the postData function it returns "XMLHttpRequest cannot load http://mywebsite.com/Home/Login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access."

    and this API is made on .NET

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. Work like Charm, i have learnt a lot from it greatly, thanks

    ReplyDelete
  18. never mind my previous comment requesting help on alertbox. i got it working :D

    ReplyDelete
    Replies
    1. @CJD, kindly show how you fixed it. Thanks

      Delete
  19. hello sir. please i am getting this error upon signup. my tabs page is not showing and my signup datas are storing into my database.

    Runtime Error
    Unexpected token < in JSON at position 0
    Stack
    SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse ()
    at Response.Body.json (http://localhost:8100/build/vendor.js:66426:25)
    at SafeSubscriber._next (http://localhost:8100/build/main.js:324:29)
    at SafeSubscriber.__tryOrUnsub (http://localhost:8100/build/vendor.js:36172:16)
    at SafeSubscriber.next (http://localhost:8100/build/vendor.js:36119:22)
    at Subscriber._next (http://localhost:8100/build/vendor.js:36059:26)
    at Subscriber.next (http://localhost:8100/build/vendor.js:36023:18)
    at XMLHttpRequest.onLoad (http://localhost:8100/build/vendor.js:66855:38)
    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:9967)
    at Object.onInvokeTask (http://localhost:8100/build/vendor.js:4499:37)

    ReplyDelete
    Replies
    1. Did you solve this problem? Got the same here...

      Delete
  20. What happens when you start the session in two devices?

    ReplyDelete
  21. Hi Srinivas i have two errors,
    one is when i try to register a user and show me a error:
    "{error: {…}}error: text: "Enter valid data"

    and two, i register a user in mysql and trying to login show me this error

    "Bad request wrong username and password"

    can you help me please? i'm trying to understand web services
    Greetings

    ReplyDelete
    Replies
    1. Hi, Look like you haven't completed the registration process. Give valid information and try, you will get inserted user information data set.

      Delete
  22. SyntaxError: Unexpected end of JSON input

    ReplyDelete
  23. How to get details of user after login using token value.... thanks....

    ReplyDelete
    Replies
    1. Take a look at this link https://www.9lessons.info/2017/07/ionic-angular-JSON-parsing-json-APIs.html

      Delete
  24. Hai sir, I get error {"error":{"text":"Enter valid data"}} while i try signup function . please help !

    ReplyDelete
  25. Hi, I am new. Where do I physically store the api files?

    ReplyDelete
  26. Hi! Where do I store the api files?

    ReplyDelete
    Replies
    1. Install XAMPP(Apache PHP MySQL) server and copy api file in htdocs folder.

      Delete
  27. Hi sir,
    This code error after i m update cordove to version 7.1.0 :

    Typescript Error
    Argument of type '{ headers: Headers; }' is not assignable to parameter of type 'RequestOptionsArgs'. Types of property 'headers' are incompatible. Type 'Headers' is not assignable to type 'Headers'. Two different types with this name exist, but they are unrelated. Property 'keys' is missing in type 'Headers'.
    D:/ionic/ionic-welcome/src/providers/auth-service/auth-service.ts
    this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers})
    .subscribe(res => {

    ReplyDelete
  28. Hi Sir,
    Error when build or run on android device

    ReplyDelete
  29. hi sir,
    i like yours lessons. thanks so much.
    My question is; what is your text editor software you are using to open projet?
    Thanks so much

    ReplyDelete
  30. when i apply setTimeout function... no action performed :(

    ReplyDelete
  31. when i use setTimeout function .. no action perform :(

    ReplyDelete
  32. If any tutorial available Ionic with C#.net web api code? pls help?

    ReplyDelete
  33. I resolved the error " Enter Valid Data". Basically, we have data validity check in our API. So PREG_MATCH does this logic. If you provide valid credentials while you enter the details for Sign-up. it works fine. For example, make sure you have alphanumeric value for password & right input for email & so on. It should work fine!..

    Thank you Srinivas!, very nice tutorial

    ReplyDelete
  34. my first ionic app create using this post...
    very helpful post..
    thanks very much...

    ReplyDelete
  35. Hi Srinivas,

    The error is displayed when calling singup in app

    ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'user_id' of undefined
    TypeError: Cannot read property 'user_id' of undefined
    at new HomePage (home.ts:21)

    What´s wrong?

    ReplyDelete
    Replies
    1. Modify following code.

      localStorage.setItem('userData', JSON.stringify(this.responseData));
      this.navCtrl.push(TabsPage);

      to

      if(this.responseData.userData)
      {
      localStorage.setItem('userData', JSON.stringify(this.responseData));
      this.navCtrl.push(TabsPage);
      }

      Delete
    2. console.log(this.responseData.userData) = undefinded ?? why? pls help!

      Delete
  36. nice post bro... i really like that... you helping me to learn about ionic...

    ReplyDelete
  37. Hi Srinivas,

    at first I want to thank you for this great tuturial.

    I have problem when I try to Signup to my Database. The user is created in my Database, but I've get this Error in my Browser:

    ERROR
    SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 2 of the JSON data
    Stack trace:
    [email protected]://localhost:8100/build/vendor.js:66955:20
    [155]/AuthServiceProvider.prototype.postData/</<@http://localhost:8100/build/main.js:143:25
    [email protected]://localhost:8100/build/vendor.js:33683:13
    [email protected]://localhost:8100/build/vendor.js:33630:17
    [email protected]://localhost:8100/build/vendor.js:33570:9
    [email protected]://localhost:8100/build/vendor.js:33534:13
    [email protected]://localhost:8100/build/vendor.js:67448:21
    F</l</[email protected]://localhost:8100/build/polyfills.js:3:15649
    [email protected]://localhost:8100/build/vendor.js:4973:24
    F</l</[email protected]://localhost:8100/build/polyfills.js:3:15562
    F</c</[email protected]://localhost:8100/build/polyfills.js:3:10815
    F</h</[email protected]://localhost:8100/build/polyfills.js:3:16787
    [email protected]://localhost:8100/build/polyfills.js:2:27646
    [email protected]://localhost:8100/build/polyfills.js:2:27893
    core.js:1350

    defaultErrorLogger
    core.js:1350
    ErrorHandler.prototype.handleError
    core.js:1411
    IonicErrorHandler.prototype.handleError
    ionic-error-handler.js:61
    next
    core.js:5376:134
    EventEmitter.prototype.subscribe/schedulerFn<
    core.js:4223:34
    SafeSubscriber.prototype.__tryOrUnsub
    Subscriber.js:238
    SafeSubscriber.prototype.next
    Subscriber.js:185
    Subscriber.prototype._next
    Subscriber.js:125
    Subscriber.prototype.next
    Subscriber.js:89
    Subject.prototype.next
    Subject.js:55
    EventEmitter.prototype.emit
    core.js:4203:22
    onHandleError/<
    core.js:4651:48
    F</l</t.prototype.invoke
    http://localhost:8100/build/polyfills.js:3:14974
    F</c</r.prototype.run
    http://localhost:8100/build/polyfills.js:3:10124
    NgZone.prototype.runOutsideAngular
    core.js:4577:47
    onHandleError
    core.js:4651
    F</l</t.prototype.handleError
    http://localhost:8100/build/polyfills.js:3:15054
    F</c</r.prototype.runTask
    http://localhost:8100/build/polyfills.js:3:10869
    F</h</e.invokeTask
    http://localhost:8100/build/polyfills.js:3:16787
    p
    http://localhost:8100/build/polyfills.js:2:27646
    v
    http://localhost:8100/build/polyfills.js:2:27893

    I can't finde the mistake. Can you help me with this?

    Thank you in advance


    ReplyDelete
    Replies
    1. Check your signup resful api with chrome POSTman

      Delete
    2. Thank you for your reply. With Postman I get no error. In Chrome I get this error:

      ERROR SyntaxError: Unexpected token < in JSON at position 1
      at JSON.parse ()
      at Response.Body.json (http.js:1063)
      at SafeSubscriber._next (auth-service.ts:21)
      at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
      at SafeSubscriber.next (Subscriber.js:185)
      at Subscriber._next (Subscriber.js:125)
      at Subscriber.next (Subscriber.js:89)
      at XMLHttpRequest.onLoad (http.js:1556)
      at t.invokeTask (polyfills.js:3)
      at Object.onInvokeTask (core.js:4620)

      Delete
    3. Please take the update, fixed the signup part.

      $git pull

      Delete
    4. Hello I have the same error how to do? Do you have a last update on which file?

      Delete
  38. Hi Srinivas,
    I am new to IONIC
    I am getting this error when trying to signup.
    polyfills.js:3 POST http://localhost:8100/undefinedsignup 404 (Not Found)
    The data is inserting in postman. but not from app.
    Please help
    Thanks in advance

    ReplyDelete
  39. First i have to thanks for this great article....only i have not been able to get it to work..i get the following error.

    Can't resolve all parameters for HomePage: ([object Object], ?).

    pls help

    ReplyDelete
  40. Please help!
    I'm getting {"error":{"text":"Enter valid data"}} when i try to test the signup endpoint from fiddler

    This is how my request body looks:
    {
    username: "Tamada",
    password: "ade123",
    email: "[email protected]",
    name: "Srinivas Tamada"
    }

    ReplyDelete
  41. I taken the last version but In Chrome I get this error anyways:

    ERROR SyntaxError: Unexpected token < in JSON at position 1
    at JSON.parse ()
    at Response.Body.json (http.js:1063)
    at SafeSubscriber._next (auth-service.ts:21)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
    at SafeSubscriber.next (Subscriber.js:185)
    at Subscriber._next (Subscriber.js:125)
    at Subscriber.next (Subscriber.js:89)
    at XMLHttpRequest.onLoad (http.js:1556)
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.js:4620)

    And when i try to login i'm stucked at "Please Wait" pop-up

    Help me, thanks

    ReplyDelete
  42. I have error in auth-service this.http.post(apiurl+type, JSON.stringify(credentials), {headers:headers}).subscribe(res =>{
    resolve(res.json());

    ReplyDelete
  43. Hi Srinivas,
    This code error after i m update cordove to version 7.1.0 :

    Typescript Error
    Argument of type '{ headers: Headers; }' is not assignable to parameter of type 'RequestOptionsArgs'. Types of property 'headers' are incompatible. Type 'Headers' is not assignable to type 'Headers'. Two different types with this name exist, but they are unrelated. Property 'keys' is missing in type 'Headers'.
    D:/ionic/ionic-welcome/src/providers/auth-service/auth-service.ts
    this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers})
    .subscribe(res => {

    ReplyDelete
  44. 404 Page Not Found
    when trying to access signup and so as other functions. Please help. Thanks

    ReplyDelete
  45. Please give me solution for this error
    When I submit data at time I get error invalid character and data not inserted into database

    ReplyDelete
  46. This is video too much help-full and work for me
    Thanks bro.

    ReplyDelete
  47. tengo este error core.js:1350 ERROR SyntaxError: Unexpected token < in JSON at position 1
    at JSON.parse ()
    at Response.Body.json (http.js:1063)
    at SafeSubscriber._next (auth-service.ts:20)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
    at SafeSubscriber.next (Subscriber.js:185)
    at Subscriber._next (Subscriber.js:125)
    at Subscriber.next (Subscriber.js:89)
    at XMLHttpRequest.onLoad (http.js:1556)
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.js:4620)

    ReplyDelete
  48. when click submit button i got

    TypeError: res.json is not a function
    at SafeSubscriber._next (http://localhost:8100/build/main.js:519:29)
    at SafeSubscriber.__tryOrUnsub .......

    please help,
    (i'm using ionic 3 angular 5)

    ReplyDelete
  49. Hi, I Followed your video tutorials,when users signup,that those datas are stored correctly..but my issue is,when clicking the signup button its not moving to tabs page...but in console there is no issue...have any idea??

    ReplyDelete

Make in India