【问题标题】:How do I get a key for jsonwebtoken secret?如何获取 jsonwebtoken 密钥的密钥?
【发布时间】:2018-11-29 07:44:37
【问题描述】:

我正在为 Node.js 使用 jsonwebtoken 模块。如何获取jwt.sign 函数的密钥:jwt.sign(payload, secretOrPrivateKey, [options, callback])

根据文档:

secretOrPrivateKey 是一个字符串、缓冲区或对象,其中包含 HMAC 算法的秘密或 RSA 和 ECDSA 的 PEM 编码私钥。如果私钥带有密码,则可以使用对象 { key, passphrase }(基于加密文档),在这种情况下,请确保您传递算法选项。

示例中使用的密钥是“shhhh”,但这可能不安全: var jwt = require('jsonwebtoken'); var token = jwt.sign({ foo: 'bar' }, 'shhhhh');

如何获取/生成更好的密钥?

【问题讨论】:

    标签: node.js express jwt express-jwt


    【解决方案1】:

    首先你应该使用openssl生成私钥和公钥,在linux的命令行中执行两个步骤

    第一步

    openssl genrsa -out private-key.pem 1024
    

    第二步。

    openssl rsa -in private-key.pem -out public-key.pem -outform PEM -pubout
    

    现在可以这样写jwt代码了。

    const fs = require('fs');
    const jwt = require('jsonwebtoken');
    const path = require('path');
    const jwtPrivateKey = path.resolve('') + '/keys/private_key.pem';
    const jwtPublicKey = path.resolve('') + '/keys/public_key.pem';
    
    module.exports.generateToken = async(id, name, type) => {
      const payload = {
        id: id,
        name: name,
        type: type
      };
      const token = await  jwtSign(payload);
      return token;
    };
    
    module.exports.verifyToken = async(token) => {
      const result = await jwtVerify(token);
      return result;
    };
    
    module.exports.getPayloadFromToken = async(token) => {
      const payload = await jwtVerify(token);
      return payload;
    };
    
    const jwtSign = (payload) => {
      const options = {
        algorithm: 'RS256',
        expiresIn: '24h'
      }
      return new Promise((resolve, reject) => {
        try {
          const cert = fs.readFileSync(jwtPrivateKey);
          const token = jwt.sign(payload, cert, options);
          resolve(token);
        } catch (err) {
          reject(err);
        }
      })
    }
    
    const jwtVerify = (token) => {
      const options = {
        algorithms: ['RS256']
      }
      return new Promise((resolve, reject) => {
        try {
          const cert = fs.readFileSync(jwtPublicKey);
          const result = jwt.verify(token, cert, options);
          resolve(result);
        } catch (err) {
          reject(err);
        }
      })
    }
    

    【讨论】:

      【解决方案2】:

      要创建我喜欢使用的“安全”随机密码:Linux 上的openssl rand -base64 60。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-29
        • 2017-05-09
        • 2021-07-26
        • 1970-01-01
        • 2013-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多