Skip to main content

Ionic2 - Secure Storage in mobile application

Securing communication between mobile application and back-end server is crucial. We should authenticate the requests sent from mobile applications before serving them. Authentication may require username and password for the user, which most of the developers store into mobile local-storage.  Storing sensitive information in local-Storage is a very bad practice, instead you should use other options such as JWT tokens or Social providers. To get more information look to Security for Cordova mobile applications.

An token is also an sensitive information, which we need to store somewhere, so what shall we do?
Thank God cordova have such large community support, we will look for one of such plugin which can help us here.

Before using plugin, lets first create the blank ionic2 application

ionic start --v2 SecureStorageExample blank

navigate to the directory of your application  and add the secure storage plugin using the below command

ionic plugin add cordova-plugin-secure-storage

once the plugin get's added, our plugin folder will have one more directory for secure storage as shown


now let's open app.module.ts and import SecureStorage

import { SecureStorage } from 'ionic-native';


now add secure storage into providers of module, which will make our code to look something like below
import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { SecureStorage } from 'ionic-native';


import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    SecureStorage,
    { provide: ErrorHandler, useClass: IonicErrorHandler }]
})
export class AppModule { }

now let's see secure storge in action. first we will import SecureStorage in app.component.ts. Change the app.component.ts as shown

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';

import { HomePage } from '../pages/home/home';
import { SecureStorage } from 'ionic-native';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage = HomePage;

  constructor(platform: Platform, secureStorage: SecureStorage) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
      //name of our secure storage application, if it's already created then it won't be created
      secureStorage.create('funWithHybrid').then(
        () => {
          console.log("Secure Storage is ready");
        },
        (error) => {
          //there should be screen lock available in your application with pin or pattern
          console.log(error);
        }
      );
    });
  }
}


Let me explain the above code to you. First we will create a secure storage specific to our application. here we will name it "funWithHybrid". This is a one time activity, the create method within SecureStorgae will create the storage if it's not present, else it won't do anything.
Note: SecureStorage plugin will throw error, if there no lock screen is set  with pin/pattern to mobile. Many new developers have reported this as bug, but the cause always seem to be no lock screen.

Now we can set our key anywhere in the example, for demo purpose we will set an key and try to fetch it within one page. Let's set this all in our home.ts, but before that we need to know about two methods:


  • set('keyName','KeyValue') : This method will be used to set any key value with two parameters. it takes input in string type.
  • get('keyName') : This method is used to get key value from storage. It returns output in string format. 
Update home.html and home.ts as shown below
home.html


  
    
      Secure Storage Example
    
  



 
    
      Set Key Value
    
    
      Set Key
      
    
    
      
    
    
      Get Key Value
    
    
      
    
    
      

Get Key value: {{getValue}}


home.ts

import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';
import { SecureStorage } from 'ionic-native';

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

  private getValue: string;
  private setValue: string;

  constructor(public navCtrl: NavController, public secureStorage: SecureStorage) {

  }

  private setKey():void {
    //set token/key for your application, although you can set anywhere
    console.log('set called');
    console.log(this.secureStorage);
    this.secureStorage.set('mytoken', this.setValue)
      .then(
      data => console.log(data),
      error => console.log(error)
      );
  }

  private getKey():void {
    console.log('get called');
    this.secureStorage.get('mytoken')
      .then(
      data => {
        this.getValue = data;
      },
      error => {
        console.log(error)
      }
      );
  }

}


Here in setkey(), we will first try to set the value for our key by calling set() method of Secure Storage. In getKey() we try to fetch the same value from secure storage. This marks the end of our simple example. Github link for Example

Comments

  1. I like this article of yours
    but...

    everytime i try go set or get something i get the message:
    Runtime Error Cannot read property 'set' of undefined
    or
    Runtime Error Cannot read property 'get' of undefined

    could you help me?

    ReplyDelete
    Replies
    1. Could you provide us your code on github and make sure to install cordova-plugin-secure-storage plugin in your application.

      Delete
  2. Hi, i try do like your text and i get error:
    Property 'set' does not exist on type 'SecureStorage';

    And not compile my code. Should be a newer version?
    Now is require SecureStorageObject.

    ReplyDelete
  3. Great explanation to given on this post and i read our full content was really amazing, then the more important in my part of life. The given information very impressed for me really so nice content.
    Mobile App Development Company In Chennai
    Android App Development Company In Chennai
    Android Application Development Company In Chennai
    Custom Web Application Development Company In Chennai

    ReplyDelete
  4. This is really helpful and informative, as this gave me more insight to create more
    ideas and solutions for my plan.keep update with your blog post.

    Website Design Company in Bangalore
    Website Development Company in Bangalore

    ReplyDelete

Post a Comment

Popular posts from this blog

Ionic2 - Hammer JS Example

Gesture event support is also one of the reason behind popularity of mobile applications. Capturing gesture events can be easily done in case of native mobile applications, since all the mobile platform expose gesture events in native code. Since Hybrid mobile applications are built over html and  javascript,  html don't support gesture events. There could be scenario's, where you wants to provide support for your hybrid mobile application. In such cases, we can use Hammer.JS  . Angular version 2 also provides support for Hammer.JS, about the same we will look into this post. Let's say we want to design a simple box, which we can rotate in any direction as shown Here we are trying to rotate the box in any direction by using Gesture events. To perform rotation we need to use two fingers. Let's see how we can implement the same in Ionic. Let's create a blank application using command ionic start hammerjsExample blank --v2 Now let's add Hammer.JS ...

Ionic2 - Internationalization using ng2-translate

To target target people from different countries, i18n support is required for your mobile app . Here in India where there are so many local languages, i18n support in mobile apps is must. In This blog, we will look how we can achieve i18n in ionic2 apps. We all know ionic2 is based on angular version 2. New angular version has it's own internationalization(i18n) approach , but sadly this approach is not yet supported in ionic2. Ionic team suggests to use ng2-translate for the internationalization in ionic2. Let's begin with it Create a blank application in ionic2 ionic start --v2 i18Ionic blank navigate to folder i18Ionic in terminal/cmd and install ng2-translate npm package in your ionic project npm install ng2-translate --save Once the npm package is installed, we are ready to configure our application for i18n support. in ng2-translate, we need to create json specific to the languages which we want to support in our code. In this example we will s...