📜  jwt decode - Javascript (1)

📅  最后修改于: 2023-12-03 15:02:28.396000             🧑  作者: Mango

JWT Decode - JavaScript

JSON Web Tokens (JWTs) are a popular method of securely transmitting information between two parties. JWTs consist of three portions: the header, the payload, and the signature. The header and payload are Base64-encoded JSON strings and the signature is generated using a secret key.

In order to decode a JWT, one must have access to the secret key. Once decoded, the payload can be read and its information used as needed.

In JavaScript, decoding a JWT can be done using the jwt-decode package. This package is lightweight and easy to use.

Installation

To use jwt-decode, first install the package using npm:

npm install jwt-decode
Usage

Once installed, require the package in your JavaScript file:

const jwt_decode = require('jwt-decode');

Next, pass the JWT string to the jwt_decode function:

let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';

let decoded = jwt_decode(token);

The decoded variable will contain the decoded information from the JWT.

{
  sub: '1234567890',
  name: 'John Doe',
  iat: 1516239022
}
Conclusion

Decoding a JWT in JavaScript is a simple process using the jwt-decode package. By passing the JWT string to the jwt_decode function and having access to the secret key, the payload information can be easily accessed and used as needed.