Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 273
Sam Avatar asked May 06 '15 23:05

Sam


People also ask

Where should I store JWT secret key?

To reiterate, whatever you do, don't store a JWT in local storage (or session storage). If any of the third-party scripts you include in your page is compromised, it can access all your users' tokens. To keep them secure, you should always store JWTs inside an httpOnly cookie.

What should be the secret key in JWT?

JWT is created with a secret key and that secret key is private to you which means you will never reveal that to the public or inject inside the JWT token. When you receive a JWT from the client, you can verify that JWT with this that secret key stored on the server.

What is JWT secret in node JS?

JSON Web Token – or JWT (pronounced 'jot') – is an access token standard used by applications to create signatures of data sent across the web. It can also encrypt payloads on JSON sent, where tokens are either signed using a private or public/private secret key.


1 Answers

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.

like image 77
Andrew Lavers Avatar answered Sep 17 '22 18:09

Andrew Lavers