Js 获取token 过期时间

function getJwtExpiration(token) {
    try {
        const base64Url = token.split('.')[1]; // 提取 payload 部分
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); // Base64Url 转换为 Base64
        const jsonPayload = decodeURIComponent(
            atob(base64)
                .split('')
                .map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
                .join('')
        );
 
        const payload = JSON.parse(jsonPayload);

        if (payload.exp) {
            // `exp` 通常是 UNIX 时间戳(秒)
            const expirationDate = new Date(payload.exp * 1000); // 转换为毫秒
            return expirationDate;
        } else {
            throw new Error("Token does not have an 'exp' field");
        }
    } catch (error) {
        console.error('Error parsing JWT:', error);
        return null;
    }
}
 
// 示例用法
const jwtToken = "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGR w";
const expiration = getJwtExpiration(jwtToken);
 
if (expiration) {
    console.log(`Token expires at: ${expiration}`);
} else {
    console.log("Failed to retrieve expiration date.");
}
posted @ 2024-12-19 14:37  Josen_Earth  阅读(14)  评论(0编辑  收藏  举报