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

前端 未结 1 1347
无人共我
无人共我 2021-01-30 13:16

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. Ex

相关标签:
1条回答
  • 2021-01-30 13:38

    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.

    0 讨论(0)
提交回复
热议问题