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

How to Decode JWT Tokens in JavaScript Without External Libraries?

Patricia Arquette
Release: 2024-11-01 00:26:28
Original
858 people have browsed it

 How to Decode JWT Tokens in JavaScript Without External Libraries?

Decoding JWT Tokens in JavaScript Without Libraries

Decoding the payload of a JWT (JSON Web Token) is essential for accessing and using its claims in a front-end application. Below are two efficient methods to decode JWT tokens without借助libraries:

Browser:

In the browser environment, we can employ the following steps to extract the JSON payload:

  1. Split the token into three parts using the dot ('.') as the delimiter.
  2. Decode the second part, which contains the payload, using base64url (RFC 4648 §5).
  3. Decode the base64url-encoded payload into a Unicode text string.
  4. Decode the Unicode string as a JSON object.

JavaScript Code:

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

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

Node.js:

Node.js offers a straightforward method for decoding JWT payloads:

  1. Split the token into three parts using the dot ('.') as the delimiter.
  2. Decode the second part, which contains the payload, using base64.
  3. Convert the decoded payload, which is a Buffer object, into a JSON object.

JavaScript Code:

<code class="javascript">function parseJwt(token) {
    const base64Payload = token.split('.')[1];
    const payloadBuffer = Buffer.from(base64Payload, 'base64');
    const payload = JSON.parse(payloadBuffer.toString());

    return payload;
}</code>
Copy after login

Note: These methods do not validate the signature of the JWT token. It is strongly recommended to use a library for signature verification to ensure token authenticity.

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