Ionic 3 and Angular 4: PHP Restful API User Authentication for Login and Signup.
Wall Script
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;
      console.log(this.responseData);
      localStorage.setItem('userData', JSON.stringify(this.responseData));
      this.navCtrl.push(TabsPage);
    }, (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 add platform ios
$ ionic build ios

Build Android App
Open Android build using Android SDK>
cordova add platform 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


27 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
  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
  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
  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. My Django REST API (django-rest-auth) is only returning the token on login. So when setItem is called on the mobile/Ionic side, the local storage only stores the token. I need to store more than just the token. I understand fields like username, first name, etc. are being locally stored when signing up, but the local storage can be erased at any time. So my thinking is that I really need to save the username, first/last name along with the token WHEN going through the login phase. Does it make sense? And if so, what do you recommend?
    Option 1: Modify my REST API to include those fields along with the token.
    Option 2: Receive the token, and concatenate it with the username the user entered when login in.
    I prefer option 1 because I can get the full user information (like first name) and then include it in my view .html page: Hi {{user.firstname}}.
    Thoughts?

    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
  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

Make in India