angular2-jwt icon indicating copy to clipboard operation
angular2-jwt copied to clipboard

Ionic 2 RC0 Support - Not specifically LocalStorage

Open gfviegas opened this issue 10 years ago • 15 comments

Hey, Ionic 2 RC0 is out and Ionic's Storage is not specifically Local Storage.

Can the plugin support us to choose the Storage? Perhaps pass the Ionic's storage as a config, or something.

from my question in #169

gfviegas avatar Sep 30 '16 20:09 gfviegas

Same for me. Not work with default locale storage.

jafaripur avatar Oct 01 '16 13:10 jafaripur

Try this:

window.localStorage.setItem('id_token', authResult.idToken); this.local.set('id_token', authResult.idToken);

lagear avatar Oct 02 '16 15:10 lagear

provide an alternate tokenGetter function in AuthConfig. If you wish to use tokenNotExpired, fetch the token first, and pass it as the second argument.

escardin avatar Oct 03 '16 13:10 escardin

@escardin as silly as it seems, when I put my token on window.localStorage, fetch it and run tokenNotExpired() it returns true. When I put the same token on the argument of tokenNotExpired(token), it returns me false.

Somehow, the tokenNotExpired with a token as an argument is not working properly, or I'm missing something here..

@lagear I thank you for the suggestion, but as far as I know it, ionic's default storage is IndexedDB now, and it returns promises as a fetch solution, so its really hard to adapt the plugin to the new storage type.

gfviegas avatar Oct 03 '16 21:10 gfviegas

@gfviegas you can choose where save the token, localstorage is still valid

lagear avatar Oct 04 '16 02:10 lagear

LocalStorage is but the default storage service from Ionic is not. I want to use ionic's storage, and not specifically local storage, that's what's the issue is all about

On 3 Oct 2016 23:04, "lagear" [email protected] wrote:

@gfviegas https://github.com/gfviegas you can choose where save the token, localstorage is still valid

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/auth0/angular2-jwt/issues/185#issuecomment-251277298, or mute the thread https://github.com/notifications/unsubscribe-auth/AF5H8YfLuCcHk3_HzYTxIMJYKmqcZ5Tiks5qwbRKgaJpZM4KLe7S .

gfviegas avatar Oct 04 '16 03:10 gfviegas

@gfviegas show me some code. I did say the token needs to be the SECOND argument.

escardin avatar Oct 04 '16 13:10 escardin

@gfviegas I solved this issue by modifying the auth.ts provider with this code:

// src/providers/auth/auth.ts
import { Storage } from '@ionic/storage';
import {AuthHttp, JwtHelper, tokenNotExpired} from 'angular2-jwt';
import {Injectable, NgZone} from '@angular/core';
import {User} from '@types/auth0'

// Avoid name not found warnings
declare var Auth0: any;
declare var Auth0Lock: any;

@Injectable()
export class AuthService {
  jwtHelper: JwtHelper = new JwtHelper();
  auth0 = new Auth0({clientID: '-----------', domain: '-------------------'});
  lock = new Auth0Lock('-----------', '-------------------', {
    auth: {
      redirect: false,
      params: {
        scope: 'openid offline_access',
      }
    },
    closable: false
  });
  refreshSubscription: any;
  user: User;
  zoneImpl: NgZone;

  constructor(public authHttp: AuthHttp, zone: NgZone, public local: Storage) {
    this.zoneImpl = zone;
    // Check if there is a profile saved in local storage
    this.local.get('profile').then(profile => {
      this.user = JSON.parse(profile);
    }).catch(error => {
      console.log(error);
    });

    if(window.localStorage.getItem('profile'))
      this.user = window.localStorage.getItem('profile');

    this.lock.on('authenticated', authResult => {
      this.local.set('id_token', authResult.idToken);
      window.localStorage.setItem('id_token', authResult.idToken);

      // Fetch profile information
      this.lock.getProfile(authResult.idToken, (error, profile) => {
        if (error) {
          // Handle error
          alert(error);
          return;
        }

        profile.user_metadata = profile.user_metadata || {};
        this.local.set('profile', JSON.stringify(profile));
        window.localStorage.setItem('profile', JSON.stringify(profile));
        this.user = profile;
      });

      this.lock.hide();

      this.local.set('refresh_token', authResult.refreshToken);
      window.localStorage.setItem('refresh_token', authResult.refreshToken);
      this.zoneImpl.run(() => this.user = authResult.profile);
    });

  }

  public authenticated() {
    // Check if there's an unexpired JWT
    return tokenNotExpired();
  }

  public login() {
    // Show the Auth0 Lock widget
    this.lock.show();    
  }

  public logout() {
    this.local.remove('profile');
    this.local.remove('id_token');
    this.local.remove('refresh_token');

    window.localStorage.removeItem('profile');
    window.localStorage.removeItem('id_token');
    window.localStorage.removeItem('refresh_token');

    this.zoneImpl.run(() => this.user = null);
  }
}

I've mixed this.local with window.localStorage because the tokenNotExpired() function works with window.localStorage. Now it works for me.

P.S: I use @type/auth0 for dealing with user-type because if not, TypeScript drops me some errors.

mllull avatar Oct 04 '16 13:10 mllull

escardin commented 9 hours ago @gfviegas show me some code. I did say the token needs to be the SECOND argument.

Why as the second? The docs are wrong then https://github.com/auth0/angular2-jwt#checking-authentication-to-hideshow-elements-and-handle-routing

gfviegas avatar Oct 04 '16 22:10 gfviegas

The thing is:

I dont want to use local storage always, and the getter token function from ionic returns a promise.

gfviegas avatar Oct 04 '16 22:10 gfviegas

@gfviegas https://github.com/auth0/angular2-jwt/blob/master/angular2-jwt.ts#L242-L249

escardin avatar Oct 05 '16 13:10 escardin

storagePromise.then(tokenData=>tokenNotExpired(undefined,tokenData));

escardin avatar Oct 05 '16 13:10 escardin

@escardin will try it, thanks bra...

We should really improve the docs..

gfviegas avatar Oct 05 '16 13:10 gfviegas

I would much rather improve the code. The docs were not wrong, but the way this function works is due to how the v1 angular router worked, and now that we have routers that can have activation dependencies, we could refactor this to be much more consistent. I'm just a volunteer though, and have not got the time available to refactor the code or update the docs.

PRs are definitely welcome though.

escardin avatar Oct 05 '16 13:10 escardin

Looks like this duplicates #11 (hardcoded use of local storage in tokenNotExpired call). Reopen if you believe this not to be the case.

escardin avatar Dec 09 '16 15:12 escardin