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:
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:
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!