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

How to Decode JWT Tokens in JavaScript Without External Libraries?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 00:26:28837browse

 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>

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>

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!

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