美文网首页
NodeJs实践JSON Web Token

NodeJs实践JSON Web Token

作者: 阿尔法_狗 | 来源:发表于2020-10-30 10:53 被阅读0次

    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

          本文链接:https://www.haomeiwen.com/subject/huspmktx.html