JS如何知道auth jwt令牌何时过期?

时间:2020-11-03 19:48:26

标签: javascript jwt jwt-auth

如何模拟本地存储中的身份验证令牌已过期?

这是jwt:

export function parseJwt(token) {
  const base64Url = token.split('.')[0];
  return JSON.parse(window.atob(base64Url));
}

export function isTokenExpired(token) {
  const t = parseJwt(token);
  if (t.exp && Date.now() < t.exp * 1000) {
    return false;
  }
  return true;
}

这是本地存储:

export const isItemExpired = value => {
  if (value.expiration && Date.now() < value.expiration) {
    return false;
  }
  return true;
};

export const getItemExpiration = () => {
  const d = new Date();
  d.setDate(d.getDate());
  return d.getTime();
};

export const setItem = (key, data, expiration) => {
  const localStorageState = data;
  if (localStorageState) {
    localStorageState.expiration = expiration || getItemExpiration();
  }
  window.localStorage.setItem(key, JSON.stringify(localStorageState));
};

export const removeItem = key => {
  window.localStorage.removeItem(key);
};

export const getItem = key => {
  let value = null;
  try {
    value = JSON.parse(window.localStorage.getItem(key));
  } catch (err) {
    return null;
  }

  return value;
};

会话刷新令牌过期时,我的应用程序引发错误。我是令牌和身份验证的新手。如何将到期时间设置为创建后的5秒钟,以便找出问题所在?

0 个答案:

没有答案