JWT:什么是一个很好的秘密密钥,以及如何将其存储在Node.js / Express应用程序中? [英] JWT: What's a good secret key, and how to store it in an Node.js/Express app?

查看:198
本文介绍了JWT:什么是一个很好的秘密密钥,以及如何将其存储在Node.js / Express应用程序中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,生成密钥的好方法是什么?我应该在我的键盘上打很多随机键来生成一个,但是必须有一个更好的解决方案。解释生成一个非常好的密钥的方法。



其次,存储密钥的好方法是什么?我可以在我的应用程序配置中写密钥,但是这意味着对源代码的妥协将危及整个系统。将秘密密钥存储在Node.js Express应用程序中有什么好的方法?

解决方案

要在程序中生成一个秘密,可以使用节点 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 decoding = jwt.verify(token,buf);
});

至于存储这个,你是绝对正确的,你绝对不要在你的源代码管理中存储秘密。更好的方法是从环境变量加载这些敏感信息,例如 process.env.MY_SECRET



另一个我看到的不常见的模式是从与代码分开存储的文件中加载密码。您可以让您的节点应用程序在〜/ .myapp / secrets.json 中查找JSON文件。


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?

解决方案

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.

这篇关于JWT:什么是一个很好的秘密密钥,以及如何将其存储在Node.js / Express应用程序中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆