简体   繁体   中英

angular2-jwt check if token is expired in component?

Is it possible to check whether a id token is expired or not inside a component of angular 2 app? I got an AuthService with the method

public isAuthenticated(): boolean {
  /* check if id_token is expired or not */
  return tokenNotExpired();
}

Used inside the template it works fine. If a user is signed out it returns false, after the user signed in angular change detection reruns the function in the template and it returns true.

Used inside a component

@Component({
  selector: 'app',
  providers: [
    Auth
  ],
  templateUrl: 'app.template.html'
})

export class AppComponent implements OnInit {

  public isAuthorized: Object = {};

  constructor(private auth: Auth) {
    this.auth.handleAuthentication();
  }

  ngOnInit() {
    console.log(this.auth.isAuthenticated());
  }
}

it does not get updated after the user signed in. A page refresh is needed. How could I solve this?

I am currently working with angular2 jwt token at my desk right now and run into the same problem. It turns out that we need to set the token in localStorage as "id_token"

From angular2-jwt:

tokenNotExpired - allows you to check whether there is a non-expired JWT in local storage . This can be used for conditionally showing/hiding elements and stopping navigation to certain routes if the user isn't authenticated

Note: tokenNotExpired will by default assume the token name is id_token unless a token name is passed to it, ex: tokenNotExpired('token_name'). This will be changed in a future release to automatically use the token name that is set in AuthConfig.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM