
本文旨在提供一种健壮且可靠的方法,用于校验存储在localStorage中的JWT(JSON Web Token) Access Token的有效性。文章将深入探讨如何处理token不存在、值为undefined、格式错误以及过期等多种情况,并提供经过优化的JavaScript代码示例,帮助开发者避免常见的陷阱,确保应用程序的安全性和用户体验。
在使用JWT(JSON Web Token)进行身份验证的Web应用中,校验Access Token的有效性至关重要。通常,Access Token会存储在客户端的localStorage中,以便在后续的请求中使用。然而,在实际应用中,我们需要考虑到各种异常情况,例如:
直接使用typeof localStorage.getItem('access_token')来判断token是否存在或是否为undefined是不准确的。localStorage.getItem('access_token')在token不存在时返回null,在token值为undefined字符串时返回字符串"undefined"。typeof null返回"object",typeof "undefined"返回"string",因此无法区分这些情况。
以下代码展示了如何正确地校验Access Token的有效性:
let accessToken = localStorage.getItem('access_token');
let currentAccessTokenUser;
if (accessToken === null || accessToken === 'undefined') {
currentAccessTokenUser = null;
} else {
try {
let decodedToken = parseJwt(accessToken);
if (Date.now() >= decodedToken.exp * 1000) {
currentAccessTokenUser = null; // Token expired
} else {
currentAccessTokenUser = decodedToken.username; // Valid token
}
} catch (error) {
currentAccessTokenUser = null; // Token not in correct format
}
}代码解释:
parseJwt 函数示例:
function parseJwt (token) {
try {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
} catch (error) {
// Handle invalid token format
console.error("Error parsing JWT:", error);
return null; // Or throw the error if you prefer
}
};注意事项:
本文提供了一种健壮且可靠的方法来校验存储在localStorage中的JWT Access Token的有效性。通过处理Token不存在、值为undefined、格式错误以及过期等多种情况,可以确保应用程序的安全性和用户体验。请务必在实际应用中进行充分的测试和错误处理,以确保代码的稳定性和可靠性。
以上就是校验JWT Access Token有效性的最佳实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号