NodeJs实践JSON Web Token

NodeJs实践JSON Web Token

JWT简介

参考

http://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html
https://github.com/auth0/node-jsonwebtoken#readme
http://www.suoniao.com/article/41059

在线生成公钥私钥

////////////////
// 参考
// http://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html
// https://github.com/auth0/node-jsonwebtoken#readme
// http://www.suoniao.com/article/41059
////////////////
const jwt = require('jsonwebtoken');
const fs = require('fs');
const getConfig = require('../../config/index');
const { TokenException } = require('../lib/HttpException');

class Jwt {
  constructor() {
    this.Config = getConfig()
  }

  createToken(userId) {
    const cert = fs.readFileSync(this.Config.secret.RSA_PRIVATE_KEY);
    const expiresIn = this.Config.secret.expirationTime;
    return new Promise((resolve) => {
      jwt.sign({
        userId,
      }, cert, { algorithm: "RS256", expiresIn: expiresIn }, (err, data) => {
        if (err) new TokenException(err);
        resolve(data)
      });
    })
  }

  verifyToken(token) {
    const cert = fs.readFileSync(this.Config.secret.RSA_PUBLIC_KEY);
    return new Promise((resolve, reject) => {
      jwt.verify(token, cert, { algorithm: "RS256" }, (err, data) => {
        if (err) new TokenException(err);
        resolve(data)
      });
    })
  }
}

你可能感兴趣的:(NodeJs实践JSON Web Token)