I'm using mysql with node.js. Something like this:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
I was just wondering if having the database credentials (user and password) hardcoded in the server doesn't compromise security.
If it does, what would be a better way of doing this?
解决方案
The best way to handle this is to have your credentials stored in environment variables. You would then access your credentials like this:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : process.env.DB_HOST,
user : process.env.DB_USER,
password : process.env.DB_PASS,
database : process.env.DB_NAME
});
connection.connect();
Then you would use a library like dotenv to set environment variables. You would put your environment variables in a .env file that is not distributed with the application, and that isn't in version control. An example .env might look like this
DB_NAME=my_db
DB_HOST=localhost
DB_PASS=secret
DB_USER=me
https://www.npmjs.com/package/dotenv - see this link for more information on using dotenv and do some research on 12 factor security in apps :)