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

孤街浪徒 提交于 2019-12-03 01:58:24

问题


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?


回答1:


To generate a secret programatically you could use node's 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.

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.



来源:https://stackoverflow.com/questions/30089604/jwt-whats-a-good-secret-key-and-how-to-store-it-in-an-node-js-express-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!