簡體   English   中英

如何檢查 JWT 令牌是否在 Angular 8 中過期

[英]How to check if JWT token is expired in Angular 8

在 Angular 8 中有哪些不同的方法可以檢查 JWT 令牌是否已過期。 到期時間為 1 小時。 工作代碼/示例將不勝感激。

選項 1 - 手動

令牌到期時間以UTC 時間格式編碼在令牌中。 因此可以根據 UTC 的當前時間手動獲取和檢查它。 嘗試以下

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

ngOnInit() {
  if (this.tokenExpired(token)) {
    // token expired
  } else {
    // token valid
  }
}

選項 2 - 使用JwtHelperService

您可以使用JwtHelperServiceisTokenExpired()方法來檢查令牌是否已經過期。

import {JwtHelperService} from '@auth0/angular-jwt';
.
.
constructor(private jwtHelper: JwtHelperService) { }

ngOnInit() {
  if (this.jwtHelper.isTokenExpired(token)) {
    // token expired 
  } else {
    // token valid
  }
}

您可以使用 Angular-JWT 包獲取令牌到期日期

 getTokenExpirationDate(token: string): Date {
    const decodedToken = helper.decodeToken(token);

    if (decodedToken.exp === undefined) { return null; }

    const date = new Date(0);
    date.setUTCSeconds(decodedToken.exp);
    return date;
  }

我在我的應用程序中實現了類似的東西,它工作正常:

this.userToken$.pipe(
            filter((token: AuthToken) => !!token),
            map((token: AuthToken) => token.expiresIn()),
            tap((expiresIn: number) => console.log('token expires in', expiresIn / 1000 / 60, 'minutes')),
            switchMap((expiresIn: number) => timer(expiresIn)),
        ).subscribe(() => {
            console.warn('token expires');
            this.logout();
        });

這樣,用戶在嘗試執行新請求時不會注銷,而是在令牌過期時立即注銷。

    const jwtToken = JSON.parse(atob(response.jwtToken.split('.')[1]));
    const expires = new Date(jwtToken.exp * 1000);
    const timeout = expires.getTime() - Date.now();
    setTimeout(() => this.logout(strategyName), timeout);

我使用 setTimeout 實現了這個,它會在令牌過期時自動注銷

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM