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

1

46

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?

Seedbed answered 6/5, 2015 at 23:51 Comment(0)
A
39

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.

Antipathetic answered 7/5, 2015 at 0:54 Comment(7)
I decided to go with the suggestion to use a json file. This way, my app can simply import the contents of this file, and I can write it in my .gitignore file so it wont be included in source control. Another great thing is that I can store these files in backup locations in case they get lost.Seedbed
Also, I used the buf.toString('base64') method to convert it into text that can be stored in a file.Seedbed
+1 for environment variables. Works perfectly with process managers like PM2 or in IDEs that let you specify env variables.Niigata
Adding since it isn't mentioned here - using a file outwith version control is fine, but you must be sure to lock down access to that file such that it can only be read by the users/processes which require it.Rapacious
If I have multiple nodes running at the same time, then I'd get different keys. How can I fix this?Phototransistor
If you load your secret in an env var then all of your nodes will have access to it. If you’re talking about generating secrets at runtime then yes nodes will all generate different values as they should. Not sure why that’s a problem. There are ways for nodes to communicate with each other.Antipathetic
how to generate a key in .env file like larave did by using commandFrogfish

© 2022 - 2024 — McMap. All rights reserved.