NodeJS 可以在浏览器中使用jsonwebtoken

2q5ifsrm  于 2023-05-06  发布在  Node.js
关注(0)|答案(1)|浏览(194)

我想解析JWT令牌,发现了这个jsonwebtoken lib https://www.npmjs.com/package/jsonwebtoken,它似乎是为NodeJS设计的。可以在浏览器中使用这个库吗?我试过,但我犯了这个错误:

ymmetricKeyDetailsSupported.js:3 Uncaught ReferenceError: process is not defined
    at ./node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js (asymmetricKeyDetailsSupported.js:3:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./node_modules/jsonwebtoken/lib/validateAsymmetricKey.js (validateAsymmetricKey.js:1:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./node_modules/jsonwebtoken/verify.js (verify.js:6:1)
    at options.factory (react refresh:6:1)
.

似乎有一些问题与浏览器。我该怎么做才能解决这个问题?进程似乎只有nodejs包含浏览器中不存在的内容。这是我的typescript代码:

isTokenNeedRefresh: (seconds: number) => {
        const accessToken = localStorage.getItem(WheelGlobal.ACCESS_TOKEN_NAME);
        const decodedToken = jwt.verify(accessToken, "secret");
        const exp = decodedToken.exp;
        const now = Math.floor(Date.now() / 1000);
        // seconds was the token prereload time gap
        const isExpired = exp < now + seconds;
        if (isExpired) {
            return true;
        }else{
            return false;
        }
    }
yc0p9oo0

yc0p9oo01#

在我看来,从设计Angular 来看,在浏览器端解码JWT并提取头部或有效负载来查看它是否过期并不是一个好的做法,最好在接收令牌时检索过期时间作为属性,并在需要时存储和检索它,例如:

{
"access_token": <SOME JWT TOKEN>
"expire_in": <SOME DATE OR UNIX TIMESTAMP>
...
}

但是如果你想这样做,因为JWT头和有效负载是用base64url-encoded format编码的,你可以使用window.atob来解析它。对于headers,应该是这样的:

const jwt = '<YOUR JWT TOKEN>';
const headerBase64 = jwt.split('.')[0];
const base64 = headerBase64.replace(/-/g, '+').replace(/_/g, '/');
const decodedHeaders = JSON.parse(window.atob(base64));

console.log(decodedHeaders);

这同样适用于JWT的payload

const jwt = '<YOUR JWT TOKEN>';
const payloadBase64 = jwt.split('.')[1];
const base64 = payloadBase64.replace(/-/g, '+').replace(/_/g, '/');
const decodedJwt = JSON.parse(window.atob(base64));

console.log(decodedJwt);

我希望这对你解决问题有帮助

相关问题