Angular2-jwt and Ionic Storage. (Ionic2 RC0)

Hello,

I noticed that Ionic Storage now writes out to an IndexedDB using localforage. Angular2-jwt expects the value to be in local storage.

Is there anyway for me to tell Ionic Storage to use local storage like in previous versions?

I tried importing localforage and setting the driver to localstorage but this is not working.

Any suggestions will be appreciated.

Regards,
Niall

2 Likes

I have similar issue with JWT.

What issue are you having? Have you also tried using localforage locally?

localstorage work now

Could you show some code on this one? I am having quite a time trying to configure local storage to work with the token.

let local: Storage = new Storage();

export function getAuthHttp(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig({
          tokenName: 'id_token',
          headerPrefix: 'JWT',
          tokenGetter: (() => local.get('id_token')),
          globalHeaders: [{'Content-Type':'application/json'}],
     }), http, options);
}

When I make any authHttp request, I get a token.split is not a function error. I am thinking its because the tokenGetter cannot handle the promise returned by local.get()

EDIT: I got this to work with localStorage.getItem() the window global objects use of local storage.

¡Hola!

Here I share a piece of working code I am using on my own app

app.module.ts

import { Storage } from '@ionic/storage';
import { Http } from '@angular/http';
import { AuthHttp, AuthConfig } from "angular2-jwt";

/*
function getAuthHttp can't be anonymous (i.e. try with an exported function)
getAuthHttp depends on Http and Storage
*/
export function getAuthHttp(http: Http, storage: Storage): AuthHttp {
  return new AuthHttp( new AuthConfig({
    globalHeaders: [{ 'Content-Type': 'application/json' }],
    tokenGetter: storage.getItem('my_token_name')
  }), http);
}

app.module.ts (providers section)

  providers: [
    ...
    {
      provide: AuthHttp,
      useFactory: getAuthHttp,
      //getAuthHttp (previous line) depends on Http and Storage (see first code piece)
      deps: [Http, Storage]
    }
  ]

My actual code uses more complicated getAuthHttp function, here I show a simplified version that behaves the same as auth0’s example.

Good luck!

Saludos,