我如何获得 jsonwebtoken secret 的密钥?

How do I get a key for jsonwebtoken secret?

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

根据文档:

secretOrPrivateKey is a string, buffer, or object containing either the secret for HMAC algorithms or the PEM encoded private key for RSA and ECDSA. In case of a private key with passphrase an object { key, passphrase } can be used (based on crypto documentation), in this case be sure you pass the algorithm option.

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

我怎样才能 get/generate 一个更好的密钥?

要创建 "secure" 个我喜欢使用的随机密码:openssl rand -base64 60 on Linux。

首先,您应该在 linux

上按照命令行中的两个步骤使用 openssl 生成私钥和 public 密钥

第一步

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);
    }
  })
}