简体   繁体   中英

Decoding a JWT token on frontend with atob gives me failed to execute 'atob' on 'window' error

On frontend I am checking if my JWT is expired.

Function is:

tokenExpired(token: string) {
    const expiry = JSON.parse(window.atob(token.split('.')[1])).exp;
    return Math.floor(new Date().getTime() / 1000) >= expiry;
  }

And then using this function like:

 if (!this.tokenExpired(this.jwtToken || '')) {
      this.getAccountData().subscribe(
        (data) => {
          this.accout = data;
          this.isLoggedIn();
        },
        (err) => {
          this.isLoggedIn$.next(2);
        }
      );
    } else {
      this.isLoggedIn$.next(2);
    }

When I build my application it gives me an error in console.log: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

What are some alternatives to use instead of atob or window.atob?

Thank you!

SOLVED --> solution:

 tokenExpired(token: string) {
    if (token !== '') {
      const expiry = JSON.parse(atob(token.split('.')[1])).exp;
      return Math.floor(new Date().getTime() / 1000) >= expiry;
    } else {
      return false;
    }
  }

Is this solution a good practice? It doesn't give me an error

Instead of

const expiry = JSON.parse(window.atob(token.split('.')[1])).exp;

Use

const expiry = JSON.parse(atob(token.split('.')[1])).exp;

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