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.

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));
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
);
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 {}
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);
});
});
}
}
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);
}
}
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>
<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_id = this.userDetails.user_id;
this.userPostData.token = this.userDetails.token;
}
backToWelcome(){
const root = this.app.getRootNav();
root.popToRoot();
}
logout(){
localStorage.clear();
setTimeout(() => this.backToWelcome(), 1000);
}
}
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_id = this.userDetails.user_id;
this.userPostData.token = this.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>
<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
$ ionic build ios
Build Android App
Open Android build using Android SDK>
$ cordova platform add android
$ ionic build android
$ ionic build android

