正确隐藏数据库凭证 [英] Correctly hiding database credentials

查看:70
本文介绍了正确隐藏数据库凭证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可能会看到,我有我的数据库连接文件和另一个受保护的"文件,其中包含我的凭据,并且此文件包含在.gitignore中.我导入它并到达数据.很基本的.因此,我的问题是:

As you may see, I have my db connection file and another "protected" file, where my credentials are, and this file is included in .gitignore. I import it and reach the data. Quite basic. Therefore my questions are:

  1. 这是正确的方法吗?
  2. 如果没有,我该怎么办?另外:如何为我的帐户和连接增加额外的安全性?
  3. 假设我有一个私人收藏,没人可以看到,我该如何特别保护这个收藏?我的意思是说,用密码或两步验证.

当前代码:

const mongoose = require("mongoose");
const mongoCredentials = require("../protected/mongoCredential");

const URI = `mongodb+srv://${mongoCredentials.username}:${mongoCredential.password}
              @firstcluster-eldi8.mongodb.net/culturapp?retryWrites=true&w=majority`;

mongoose.connect(URI, { useUnifiedTopology: true, useNewUrlParser: true })
  .then(db => console.log("MongoDB is connected"))
  .catch(err => console.log(">> ERROR: ",err));

module.exports = mongoose;

推荐答案

...我有我的数据库连接文件和另一个受保护的"文件(我的凭据在其中),并且此文件包含在.gitignore中.我导入它并到达数据.

...I have my db connection file and another "protected" file, where my credentials are, and this file is included in .gitignore. I import it and reach the data..

正确的方法是使用环境变量.

环境变量是在环境上设置的,即您的本地开发计算机或远程生产服务器. 然后,在您的应用程序中,读取环境变量并适当地使用它们.

Environmental variables are set on the environment, i.e your local development machine or the remote production server. Then, within your app, you read the environment variables and use them appropriately.

通常至少有以下两个原因:

There's (at least) a couple reasons it's usually done like this:

  • 查看存储库内容的人员可以读取的文件中不存在凭据.克隆存储库的人不需要知道您的数据库凭据.
  • 环境之间的凭据可能有所不同.您可能会在本地开发计算机上使用其他数据库,而在远程生产服务器中使用其他数据库.

这是设置环境变量的方式(这适用于Linux,其他操作系统可能有所不同):

Here's how you set environment variables (this is for Linux, other OS's might be different):

$ export MONGO_DB_USERNAME=foo
$ export MONGO_DB_PASSWORD=bar

以下是在Node.js中阅读它们的方式:

and here's how you read them within Node.js:

console.log(process.env.MONGO_DB_USERNAME) // logs 'foo'
console.log(process.env.MONGO_DB_PASSWORD) // logs 'bar'

或在启动时将变量传递给进程

或者,您可以在启动过程时像这样传递变量:

or pass variables to the process when starting up

Alternatively, you can pass variables when starting up the process like so:

$ MONGO_DB_USERNAME=foo MONGO_DB_PASSWORD=bar node app.js

但是通常不建议这样做,因为您很可能是通过 npm启动脚本.由于定义了npm start命令的package.json始终提交到存储库,因此无法实现隐藏凭据的整个目的.

However that's generally discouraged since you're most probably starting your process through the npm start script. Since package.json, where the npm start command is defined, is always committed to the repository it defeats the whole purpose of hiding the credentials.

这篇关于正确隐藏数据库凭证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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