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

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

问题描述

如您所见,我有我的数据库连接文件和另一个受保护"文件,我的凭据在其中,并且该文件包含在 .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;

推荐答案

...我有我的 db 连接文件和另一个受保护"文件,我的凭据所在的位置,并且该文件包含在 .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天全站免登陆