Skip to content

Latest commit

 

History

9 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build Status NPM GitHub package.json version (branch) GitHub last commit GitHub code size in bytes

导航(Guide)

Document-EN

简介(Introduction)

fd-simple-jwt是一款使用纯JS开发的简单JWT工具。无任何第三方依赖包,能够保持该工具处于一个高度源码级定制的水准。

特色(Features)

  • 轻量级
  • 使用方便
  • 源码级定制
  • 无第三方依赖

安装(Install)

npm install fd-simple-jwt --save

中国大陆地区请使用cnpm

cnpm install fd-simple-jwt --save

使用(Usage)

const SimpleJWT = require('fd-simple-jwt');

API

fd-simple-jwt共包含两个方法:

  • encodeJWT:对数据进行JWT加密操作
  • decodeJWT:对JWT格式的数据进行解密操作

encodeJWT

生成JWT字符串。

encodeJWT接受2~3个参数:

  • options
    • (必须)options.secretKey:加密使用的秘钥
  • (必须)data:所需要加密的数据(该数据将会添加到jwt数据体中在消息发送时一同发送)
    • (可选)data.expire:jwt过期时间,单位:秒(second)。如果设置了expire,解密时会自行根据创建时间(data.startTime)判断是否过期。如果过期将返回new Error('JWT expired.')
  • (可选)callback(err, jwt):回调函数。jwt是成功加密之后的jwt字符串。若不传入该回调函数,则会将jwt数据直接return回来。

直接返回

const { encodeJWT } = require('fd-simple-jwt');

const options = {
  secretKey: 'secret key', // secret为JWT的秘钥,用户需自行配置妥善保管
};
const data = {
  id: 123,
};

const jwt = encodeJWT(options, data);

回调函数

fd-simple-jwt方法第三个参数传入一个回调函数即为异步方法,回调函数贯彻错误先行原则,第一个参数为err,如果在方法执行过程中出现错误,该err参数为一个Error实例;否则为null。第二个参数为成功生成的jwt。(如果失败或错误,则回调函数不会存在第二个形参,此时的jwt变量为undefined

const { encodeJWT } = require('fd-simple-jwt');

const options = {
  secretKey: 'secret key', // secret为JWT的秘钥,用户需自行配置妥善保管
};
const data = {
  id: 123,
};

encodeJWT(options, data, function(err, jwt) {
  console.log(jwt);
})

decodeJWT

解密JWT字符串。

decodeJWT接收2~3个参数:

  • (必须)jwt:所需解密的jwt字符串。
  • (必须)secretKey:加密/解密的秘钥。
  • (可选)callback(err, data):回调函数。data是成功解密之后,jwt数据体中的数据。若不传入该回调函数,则会将解密的数据直接return回来。

直接返回

const { decodeJWT } = require('fd-simple-jwt');

const jwt = '...'; // 该值为生成的jwt字符串
const options = {
  secretKey: 'secret key',
};

const result = decodeJWT(jwt, options.secretKey);

回调函数

const { decodeJWT } = require('fd-simple-jwt');

const jwt = '...'; // 该值为生成的jwt字符串
const options = {
  secretKey: 'secret key',
};

decodeJWT(jwt, options.secretKey, function(err, data) {
  console.log(data);
})

About

A simple jwt tool

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages