如何使用Nodejs通过IAM身份验证访问RDS MySQL数据库

问题描述 投票:0回答:1

当前使用 Nodejs,我使用以下方法连接到 RDS MySQL 数据库,

const mysql = require("mysql");
const environment = require("../core/environment/environment");

const connection = mysql.createPool({
                                      host: environment.mysql.host,
                                      port: environment.mysql.port,
                                      user: environment.mysql.user,
                                      password: environment.mysql.password,        // is there a way to avoid it
                                      connectionLimit: 10
                                    });

connection.connect(function(err) {
  if (err) {
    console.error('Database connection failed: ' + err.stack);
    return;
  }

  console.log('Connected to database.');
});

connection.end();

上述方法的问题是我必须在我不想要的环境文件中公开/显示/存储密码

我最近看到这篇文章https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.Connecting.html它允许使用IAM身份验证访问数据库而不使用密码,但它不没有描述任何处理 Nodejs 平台的方法。但是,它有其他平台文章,例如 Python、.NET 等,但没有 Nodejs。

我用谷歌搜索了其他方法,但似乎找不到任何参考如何在没有密码的情况下在 Nodejs 应用程序中访问 RDS。

我怎样才能实现它?

node.js amazon-web-services amazon-rds amazon-iam
1个回答
0
投票

您可以使用

rds-signer
包(
aws-sdk
的一部分)。这应该可以帮助您使用 IAM 默认配置或 IAM 角色获取临时令牌,以安全连接到 RDS 实例。

const signer = new Signer({
  /**
   * Required. The hostname of the database to connect to.
   */
  hostname: "db.us-east-1.rds.amazonaws.com",
  /**
   * Required. The port number the database is listening on.
   */
  port: 8000,
  /**
   * Required. The username to login as.
   */
  username: "user1",
  /**
   * Optional. The AWS credentials to sign requests with. Uses the default credential provider chain in not specified.
   */
  credentials: fromNodeCredentialProvider(),
  /**
   * Optional. The region the database is located in. Uses the region inferred from the runtime if omitted.
   */
  region: "us-east-1",
  /**
   * Optional. The SHA256 hasher constructor to sign the request.
   */
  sha256: HashCtor,
});

const token = await signer.getAuthToken();

参考:https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-rds-signer/

© www.soinside.com 2019 - 2024. All rights reserved.