In this tutorial, you will learn, how to create a simple login form using the Ionic2 Framework. And authenticate the login information using the REST API(PHP REST API).

You can follow the below steps(workflow) to create simple working login application using the Ionic 2 Framework.

1. Create a simple login form such username, password field and button with click event.

2. Send these data to your server to validate the login information when the user clicks the submit button using the Http POST method.

3. Once the login is successful, Mostly the server program(PHP RESP API) will return user id and user access token. The user access token is some data to validate the user's login, which is used by many popular social media applications such as Facebook, Google, Twitter.

4. Store the server returned data such as user id and access token on the mobile application using the SQLite storage.

5. You can use the stored used id and access token to get user related information. There is no need to ask the user to login each time if you use the stored used id and access token.

About Access Token from Wikipedia.

An access token is generated by the logged-in service when a user logs on to the system and the credentials provided by the user are authenticated against the authentication database. The authentication database contains the credential information required to construct the initial token for the logged-in session, including its user id, primary group id, all other groups it is part of, and other information. The token is attached to the initial process created in the user session and inherited by subsequent processes created by the initial process. Whenever such a process opens a handle to any resource which has access control enabled, Windows reconciles the data in the target object's security descriptor with the contents of the current effective access token. The result of this access check evaluation is an indication of whether any access is allowed and, if so, what operations (read, write/modify, etc.) the calling application is allowed to perform.

To know more about access token visit the below link.

https://en.wikipedia.org/wiki/Access_token

First, we will create the login UI and the click event using Ionic 2 Framework. Then we will go develop our REST API to validate the username and password.

Preview of Login user interface using the Browser.

Create a new Ionic 2 project using the below command.

ionic start app blank --v2

Now create input fields such as username and password in the home.html file.

<ion-list>

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

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

</ion-list>

Now add a button with click event in the home.html file.

<button ion-button (click)="validateLogin()">Login</button>

That's all. The UI part is over now. We are going to use the Http class. So import the HttpModule class to the app.module.ts file.

import { HttpModule } from '@angular/http';

Include the HttpModule class to the NgModule to avoid the no provider for HTTP error or No provider for "connection backend" Problem.

@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
HttpModule
]

Now import the Http class to the home.ts file.

import {Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

Create a reference to the Http class using the constructor.

constructor(public http:Http) {

}

Now create a function with HTTP post request. And send the username and password as data.

validateLogin()
{

let headers = new Headers();
headers.append('Content-Type', 'application/json');
let data=JSON.stringify({username: this.username, password:this.password});
this.http.post('http://localhost/ionic/validateLogin.php',data,headers)
.map(res => res.json())
.subscribe(res => {
alert("success: Userid "+res.userid+" Access Token "+res.token);
}, (err) => {
alert("failed");
});

}

The validateLogin.php will validate the user inputs and returns the user id and access token. The returned response extracted and displayed in the alert box.

The validateLogin.php source code.

<?php

header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] === 'POST')
{

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$username=$request->username;
//implement your own authentication
//here i used some dummy data manually.
echo json_encode(array("userid"=>"35", "token"=>"tyresksdkjfnkjdskjsd"));

}
else
{
echo "Not allowed";
}

?>

Use the below command to preview the application using the browser.

cd app
ionic serve --lab

Storage Plugin Example.

Next, we are going to store the returned response using the Storage plugin. 

Storage is an easy way to store key/value pairs and JSON objects. Storage uses a variety of storage engines underneath, picking the best one available depending on the platform.In this example, I am using the SQLite plugin as Storage engines for Storage plugin.

Even you can use the SQLite plugin to store the returned information. The choice is yours. However, in this example, i am going to use the Storage plugin instead of SQLite plugin. If you want to learn SQLite storage plugin, then visit the below link.
https://ampersandacademy.com/tutorials/ionic-framework-version-2/sqlite-native-plugin-example

Install the SQLite, Storage plugin using the below command.

ionic plugin add cordova-sqlite-storage --save
npm install --save @ionic/storage

Import the IonicStorageModule class to app.module.ts file.

import { IonicStorageModule } from '@ionic/storage';

Next, add it to the imports list in your NgModule declaration (for example, in src/app/app.module.ts):

@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
HttpModule,IonicStorageModule.forRoot()
]

Import the Storage plugin to the home.ts file.

import { Storage } from '@ionic/storage';

Create a reference to the Storage class using the constructor.

constructor(public http:Http,private storage: Storage) {

}

Use the set method to set value and use the get method to retrieve the value. The example code is given below.

this.storage.set('userid', res.userid);
this.storage.set('token', res.token);

This can not be previewed using the browser. Why because, the browser won't support the Storage plugin. So generate the APK and test it on the Android device.

Add the Android platform using the below command.

ionic platform add android

Now generate the APK using the below command.

ionic build android

That's all. You are done. Test the generated APK using the Android device.

Tested Device.

Moto G4 Plus

 

Below is the Ionic 2 software information while writing this tutorial.


Cordova CLI: 6.5.0 
Ionic Framework Version: 3.6.0
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 2.1.3
ios-deploy version: Not installed
ios-sim version: 5.0.13 
OS: macOS Sierra
Node Version: v6.10.0
Xcode version: Xcode 8.2.1

home.html source code.

<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>

<ion-content padding>

<ion-list>

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

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


<button ion-button (click)="validateLogin()">Login</button>

</ion-list>

<button ion-button (click)="getInfo()">Get Login Info</button>

</ion-content>

home.ts source code.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { Storage } from '@ionic/storage';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

constructor(public http:Http,private storage: Storage) {

}

username='';
password=''

validateLogin()
{


let headers = new Headers();
headers.append('Content-Type', 'application/json');
let data=JSON.stringify({username: this.username, password:this.password});
this.http.post('http://localhost/ionic/validateLogin.php',data,headers)
.map(res => res.json())
.subscribe(res => {
alert("success: Userid "+res.userid+" Access Token "+res.token);


this.storage.set('userid', res.userid);
this.storage.set('token', res.token);


}, (err) => {
alert("failed");

});

}

getInfo()
{
// Or to get a key/value pair
this.storage.get('userid').then((val) => {
alert('userid is'+ val);
});
}

}