Home  >  Article  >  Web Front-end  >  How to Decode JWT Tokens in JavaScript Without Libraries?

How to Decode JWT Tokens in JavaScript Without Libraries?

Barbara Streisand
Barbara StreisandOriginal
2024-10-29 18:30:28898browse

How to Decode JWT Tokens in JavaScript Without Libraries?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn