Home >Web Front-end >JS Tutorial >How to Decode JWT Tokens Manually in JavaScript?

How to Decode JWT Tokens Manually in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 08:00:30488browse

How to Decode JWT Tokens Manually in JavaScript?

Devise a Method to Decode JWT Tokens in JavaScript

Decoding JWT tokens without utilizing libraries is possible in JavaScript. This can be achieved by manually extracting the payload from the token.

Steps for Payload Extraction:

1. Base64 Decoding:

Split the token into three parts (header, payload, signature) using the '.' character. Decode the second part (payload) using Base64URL encoding, which replaces ' ' and '/' with '-' and '_' respectively.

2. Unicode Text Replacement:

The decoded payload is a Unicode text sequence. Replace any non-printable characters (% symbols) with their corresponding ASCII codes (e.g., for a space).

3. JSON Parsing:

Finally, parse the replaced text as JSON to obtain the payload object.

Implementation:

Browser:

<code class="javascript">function parseJwt(token) {
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));

    return JSON.parse(jsonPayload);
}</code>

Node.js:

<code class="javascript">function parseJwt(token) {
    return JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
}</code>

Note: Decoding the payload does not validate the token's signature. It assumes the token has not been tampered with.

The above is the detailed content of How to Decode JWT Tokens Manually in JavaScript?. 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