简体   繁体   中英

Where should I store my secret keys for my Node.js app?

I am really struggling as to how I should hide my keys.

The two keys I need to hide are secrets.crypto and secrets.jwt... I plan on hosting my application on AWS using Elastic Beanstalk.

Also I am not sure where I would put my keys for access to things like my Dynamodb and my S3 bucket.

exports.generateToken = (type, user) => {
    if (!_.isString(type)) {
        return undefined;
     }

    try {

         //Turn the json object of the current user's id and the type of token into a string
         var stringData = JSON.stringify({
             _id: user._id,
             type: type
         });

        //Take the json string and encrypt it with a secret then turn it back into a string
        var encryptedData = cryptojs.AES.encrypt(stringData, secrets.crypto).toString();

        //Take the encryptedData and turn it into a token with a secret
        var token = jwt.sign({
            token: encryptedData
        }, secrets.jwt);

        return token;
    } catch(e) {
        return undefined;
    }
};

In Elastic Beanstalk I believe the preferred way to store keys like this is via environment variables. You can use the command eb setenv key=value to set an environment variable. More information about this here .

For accessing the AWS API, which you mention in regards to accessing DynamoDB and S3, you would not use keys at all. For this you would assign an IAM instance profile to the EC2 servers created by Elastic Beanstalk. This is documented here .

Create a configuration file for all the envoirments like development, production and add all the secret keys init and use anywhere you want.

config.json file
{
"development": {
    "Secret1": "Your Secret Here",
    "Secret2": "Your Secret Here",
    "db":{
      //development database settings here
     }
 },
   "production": {
    "Secret1": "Your Secret Here",
    "Secret2": "Your Secret Here",
    "db":{
      //development database settings here
     }
   }
}

var config = require('./config.json');
config.Secret1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM