angular2-jwt: tokenNotExpired() always return false

Hi, I use your library without Ionic (native Angular 2) and all time tokenNotExpired() method return false.

When this code is exectued :

   loggedIn() {
    console.log(tokenNotExpired());
    return tokenNotExpired();
  }

  constructor(private router: Router) {}

  canActivate() {
    console.log(this.loggedIn());
    if(this.loggedIn()) {
      return true;
    } else {
      this.router.navigate(['login']);
      return false;
    }
  }

I use this code for angular routing canActivate: [AuthGuard].

But tokenNotExpired() always return false.

I don’t understand why !

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 31 (2 by maintainers)

Most upvoted comments

I think I found the solution, as I was fighting with a similar error: The error is induced by Commit a6984d1df9315cc52b22b9c57b8badc4b6d1f47 (update token name). With this commit, angular2-jwt assumes that the standard name of the token is token , not any longer access-token. The problem can be traced to the Quickstart of Auth0 for Angular 2 (https://auth0.com/docs/quickstart/spa/angular2/01-login), as it states (as of time of writing this):

// app/auth.service.ts

import { Injectable }      from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';

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

@Injectable()
export class Auth {
  // Configure Auth0
  lock = new Auth0Lock('MyClientID', 'my.domain.dom', {});

  constructor() {
    // Add callback for lock `authenticated` event
    this.lock.on("authenticated", (authResult) => {
      localStorage.setItem('id_token', authResult.idToken);
    });
  }

  public authenticated() {
    // Check if there's an unexpired JWT
    // This searches for an item in localStorage with key == 'id_token'
    return tokenNotExpired();
  }

}

So there are two possible fixes: -Change in the constructor from localStorage.setItem('id_token', authResult.idToken) to localStorage.setItem('token', authResult.idToken)

-Use tokenNotExpired('id_token') instead of tokenNotExpired()

The third, impossible and stupid solution would be changing the default token name in JWT again.

so return !isTokenExpired()

the token is valid, so isTokenExpired should return false. It’s certainly confusing.

same problem, the function is return from localStorage but is not using the factory options of tokenGetter

The implementation with google chrome debugger is:

function tokenNotExpired(tokenName, jwt) {
    if (tokenName === void 0) { tokenName = AuthConfigConsts.DEFAULT_TOKEN_NAME; }
    var token = jwt || localStorage.getItem(tokenName);// here is force to get from localStorage but not tokenGetter options of AuthConfig
    var jwtHelper = new JwtHelper();
    return token != null && !jwtHelper.isTokenExpired(token);
}

So another options is to pass the token in second parameters.

tokenNotExpired(null, sessionStorage.getItem("id_token"))

Thank…

You can try loggedIn() { if (localStorage.getItem('token')) return tokenNotExpired() }

Thanks, @rhtpandeyIN its works

Hi all of you, I am afraid the solution proposed by @escardin is wrong. I will invite you to read the official docs of angular2-jwt, https://github.com/auth0/angular2-jwt#checking-authentication-to-hideshow-elements-and-handle-routing.

It happen to me the same but I realize my token was expired, so I was getting the correct response from tokenNoInspired(). Also I want to point out that tokenNoInspired function will by default assume the token name is token unless a token name is passed to it. Ex: tokenNotExpired(null, 'user_token')

You can find the token’s expiration date with, import {JwtHelper} from 'angular2-jwt';

jwtHelper: JwtHelper = new JwtHelper(); this.jwtHelper.getTokenExpirationDate(token)

@simeyla id_token and access_token are not the same, and they have changed it not so long ago. id_token is authentication (who you are) and access_token is authorization (it’s sent as a Bearer token to the API). in the latest version the Auth0Lock by default returns only access_token, but not the id_token. I suppose you can change your auth.service.ts to check for access-token in authenticated() method or make Auth0Lock return id_token using options. What I did in auth.service.ts is:

var options = {
  auth: {
    params: {scope: 'openid email user_metadata app_metadata picture',
             responseType: 'id_token token'},
  }
}; 
....
lock = new Auth0Lock(myConfig.clientID, myConfig.domain, options);

and then:

this.lock.on('authenticated', (authResult) => {

      localStorage.setItem('token', authResult.idToken);
      localStorage.setItem('accessToken', authResult.accessToken);

hope it helps.

Alternative solution :

Modify your auth.service.ts file:

import { AuthConfigConsts } from ‘angular2-jwt’;

Search and replace all “id_token” to AuthConfigConsts.DEFAULT_TOKEN_NAME

Had the same issue. @qmsq’s fix worked for me. Thank you.