Home > Web Front-end > JS Tutorial > body text

How to Decode JWT Tokens in JavaScript Without Libraries?

Barbara Streisand
Release: 2024-10-29 18:30:28
Original
897 people have browsed it

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];
Copy after login

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(''));
Copy after login

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();
Copy after login

4. Parse the Payload JSON

Convert the decoded payload string into JSON:

const payloadObject = JSON.parse(payload);
Copy after login

Example:

Given the token: xxxxxxxxxx.XXXXXXXX.xxxxxxxx, the decoded payload would resemble:

{exp: 10012016, name: "john doe", scope: ["admin"]}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!