jsonwebtoken、jwt-decode实现jwt获取和解析

一、jwt获取

jsonwebtoken : https://www.npmjs.com/package/jsonwebtoken

npm install jsonwebtoken

代码示例

const jwt = require('jsonwebtoken');

// 数据
const data = {
    name: "Tom",
    age: 23
}

// 秘钥
const key = "secret"

// 可选参数
const options = {
    expiresIn: '2h',   // 过期时间 eg:60="60ms", "2 days", "10h", "7d"
    algorithm: 'HS256' // 算法
}

let token = jwt.sign(data, key, options);
console.log(token);
/**
 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
 eyJuYW1lIjoiVG9tIiwiYWdlIjoyMywiaWF0IjoxNTg0MDg4OTYzLCJleHAiOjE1ODQwOTYxNjN9.
 clcR8LDC7Ncz5INgUJxIJmCJw1RzCwxXL-m_HK6FFIE
 */

二、jwt解析

1、方法一

const jwt = require('jsonwebtoken');

var decoded = jwt.decode(token);
console.log(decoded);
// { name: 'Tom', age: 23, iat: 1584088910, exp: 1584096110 }

2、方法二

jwt-decode: https://www.npmjs.com/package/jwt-decode

npm i jwt-decode

代码示例

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

decoded = jwt_decode(token)
console.log(decoded);
// { name: 'Tom', age: 23, iat: 1584088910, exp: 1584096110 }

你可能感兴趣的:(jsonwebtoken、jwt-decode实现jwt获取和解析)