NodeJS - how to securely store ip, username and password of a database?

南楼画角 提交于 2020-05-26 07:33:19

问题


I have a NODEJS code to connect to MySql database:

var mysql = require('mysql')
var express = require('express')
var app = express()

var connection = mysql.createPool({
    connectionLimit: 50,
    host     : 'ip',
    user     : 'username',
    password : 'pass',
    database : 'mydb'
});


app.get('/', function(req, resp) {
    connection.getConnection(function(error, tempCont) {
        if(!!error) {
            tempCont.release();
            console.log('Error');
        } else {
            console.log('Connected!');

            tempCont.query("select * from table", function(error, rows, fields) {
                tempCont.release();
                if(!!error) {
                    console.log('Error in the query');
                } else {
                    resp.json(rows);
                }
            });
        }
    })
})

console.log("listening requests...")
app.listen(1337);

How do I secure a ip, username and password used for connecting to a database so that is not visible in the code or configuration file?


回答1:


Install env module by : npm install --save dotenv

Create .env file at root folder and write down the code

DB_CONLIMIT=50
DB_HOST=ip
DB_USER=username
DB_PASSWORD=pass
DB_DATABASE=mydb

In your js file

var mysql = require('mysql');
var express = require('express');
var app = express();
const dotenv = require('dotenv').config();

var connection = mysql.createPool({

     connectionLimit : process.env.DB_CONLIMIT,
     host            : process.env.DB_HOST,
     user            : process.env.DB_USER ,
     password        : process.env.DB_PASSWORD ,
     database        : process.env.DB_DATABASE 
});



回答2:


You should be configuring your systems so that your service runs as its own user with its own protected files. This offers some protection so that even if another service is compromised, the intruding user's access is isolated from other components of your system. Don't run things as root.

As for how secrets are stored and accessed, that's up to you. You can have a configuration file if you want. Another option is to use environment variables. Ultimately; however, your secrets are going to have to be stored in plaintext somewhere for your system to read and use.

Another method worth mentioning is you could possibly separate your secrets from your applications by having a dedicated secrets service. All your applications would have to know about this service and from there they could request the secrets they need for their regular operation. This has the obvious caveat of all your applications depend on the secrets service on start up - if that goes down your applications won't be able to start or restart.



来源:https://stackoverflow.com/questions/52580754/nodejs-how-to-securely-store-ip-username-and-password-of-a-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!