📜  js jwt decode - Javascript (1)

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

JavaScript JWT Decode

JSON Web Tokens (JWTs) are commonly used by web applications for stateless authentication and authorization. JWTs consist of a header, a payload, and a signature, separated by period characters (.). The payload portion of the JWT contains the claims, or information about the authenticated user.

To decode a JWT in JavaScript, we can use the jwt-decode library, which provides a simple and lightweight way to parse JWTs.

Installation

To install jwt-decode, use the following command:

npm install jwt-decode
Usage
const jwtDecode = require('jwt-decode');

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';

const decoded = jwtDecode(token);

console.log(decoded);

The jwtDecode() method takes a JWT as input and returns an object containing the decoded claims.

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

The above output shows the decoded JWT payload containing the sub (subject) claim with value 1234567890, the name claim with value John Doe, and the iat (issued at) claim with value 1516239022.