Decoding JWT Tokens in JavaScript Without Libraries
Decoding the payload of a JavaScript Web Token (JWT) can be achieved without relying on external libraries. This provides greater control over the decoding process and enables seamless integration with the front-end application.
Decoding Process
The JWT format consists of three segments separated by periods, with the second segment containing the payload. To decode the payload:
1. Extract the Payload Segment:
const payloadSegment = token.split('.')[1];
2. Decode the Payload (Browser)
For browsers, the payload is encoded using base64url, which differs from regular base64. Decode it as follows:
const payload = decodeURIComponent(window.atob(payloadSegment).split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''));
3. Decode the Payload (Node.js)
In Node.js, the payload is not encoded using base64url. Decode it using the Buffer module:
const payload = Buffer.from(payloadSegment, 'base64').toString();
4. Parse the Payload JSON
Convert the decoded payload string into JSON:
const payloadObject = JSON.parse(payload);
Example:
Given the token: xxxxxxxxxx.XXXXXXXX.xxxxxxxx, the decoded payload would resemble:
{exp: 10012016, name: "john doe", scope: ["admin"]}
Note:
This method solely extracts the payload without validating the token signature. The token could have been tampered with prior to decoding.
The above is the detailed content of How to Decode JWT Tokens in JavaScript Without Libraries?. For more information, please follow other related articles on the PHP Chinese website!