简体   繁体   English

JWT:什么是一个好的秘密密钥,以及如何将它存储在Node.js / Express应用程序中?

[英]JWT: What's a good secret key, and how to store it in an Node.js/Express app?

Firstly, what's a good method of generating a secret key? 首先,生成密钥的好方法是什么? I should punch in a lot of random keys on my keyboard to generate one, but there must be a better solution to this. 我应该在键盘上输入很多随机键来生成一个,但必须有一个更好的解决方案。 Explain the way to generate a very good key. 解释生成一个非常好的密钥的方法。

Second, what's a good way to store the key? 第二,存储密钥的好方法是什么? I could write the key in my applications configuration, but that means that a compromise of the source code will compromise the entire system. 我可以在我的应用程序配置中编写密钥,但这意味着对源代码的破坏将危及整个系统。 What's good means of storing the secret key in a Node.js Express app? 在Node.js Express应用程序中存储密钥的好方法是什么?

To generate a secret programatically you could use node's crypto.randomBytes() 要以编程方式生成秘密,您可以使用node的crypto.randomBytes()

var crypto = require('crypto');
var jwt = require('jsonwebtoken');

crypto.randomBytes(256, function(ex, buf) {
  if (ex) throw ex;
  var token = jwt.sign({foo: 'bar'}, buf);
  var decoded = jwt.verify(token, buf);
});

As for storing this, you're absolutely correct, you should definitely not store secrets in your source control. 至于存储这个,你绝对正确,你绝对不应该在你的源代码管理中存储秘密。 A better way would be to load such sensitive information from environment variables, eg process.env.MY_SECRET . 更好的方法是从环境变量加载此类敏感信息,例如process.env.MY_SECRET

Another less common pattern I've seen is to load secrets from a file stored separate from your code. 我见过的另一种不太常见的模式是从与代码分开存储的文件中加载秘密。 You could have your node app look for a JSON file in ~/.myapp/secrets.json for instance. 例如,您可以让您的节点应用程序在~/.myapp/secrets.json查找JSON文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM