constfs=require('fs');constjwt=require('jsonwebtoken');// Replace these paths with your RSA private and public key filesconstprivateKeyPath='path/to/private-key.pem';constpublicKeyPath='path/to/public-key.pem';// Load the RSA private and public keysconstprivateKey=fs.readFileSync(privateKeyPath,'utf8');constpublicKey=fs.readFileSync(publicKeyPath,'utf8');// Sample payloadconstpayload= { sub:'1234567890', name:'Eason Wang', iat:Math.floor(Date.now() /1000),};// Encode (Sign) a JWT Tokenconsttoken=jwt.sign(payload, privateKey, { algorithm:'RS256' });console.log('Encoded Token:', token);// Decode (Verify) a JWT Tokenjwt.verify(token, publicKey, { algorithms: ['RS256'] }, (err, decoded) => {if (err) {console.error('JWT verification failed:',err.message); } else {console.log('Decoded Token:', decoded); }});
Decode 範例
functiondecodeJwt(token) {// Split the token into header, payload, and signatureconst [headerB64,payloadB64] =token.split('.');// Decode the base64-encoded header and payloadconstheader=JSON.parse(atob(headerB64));constpayload=JSON.parse(atob(payloadB64));return { header, payload, };}// Your JWT tokenconsttoken='YOUR_JWT_TOKEN_HERE';// Decode the JWT tokenconstdecoded=decodeJwt(token);// Access the header and payloadconsole.log('Decoded Header:',decoded.header);console.log('Decoded Payload:',decoded.payload);