

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 適用於 MariaDB、MySQL 和 PostgreSQL 的 IAM 資料庫身分驗證
<a name="UsingWithRDS.IAMDBAuth"></a>

您可以使用 AWS Identity and Access Management (IAM) 資料庫身分驗證來驗證資料庫執行個體。IAM 資料庫身分驗證可搭配 MariaDB、MySQL 和 PostgreSQL 運作。透過此身分驗證方法，您連線至資料庫執行個體時不需要使用密碼。而是改用身分驗證字符。

*身分驗證字符*是 Amazon RDS 依請求而產生的唯一字元字串。身分驗證字符是使用 AWS Signature 第 4 版產生。每個字符的存留期為 15 分鐘。您不需要將使用者登入資料存放在資料庫，因為身分驗證是利用 IAM 在外部管理。您仍可使用標準資料庫身分驗證。字符僅用於身分驗證，並且在建立後不會影響工作階段。

IAM 資料庫身分驗證提供下列優點：
+ 使用 Secure Socket Layer (SSL) 或 Transport Layer Security (TLS) 來加密往返資料庫的網路流量。如需使用 SSL/TLS 搭配 Amazon RDS 的詳細資訊，請參閱 [使用 SSL/TLS 加密與資料庫執行個體或叢集的連線](UsingWithRDS.SSL.md)。
+ 您可以使用 IAM 來集中管理資料庫資源的存取，而不需要在每個資料庫執行個體上個別地管理存取。
+ 對於 Amazon EC2 上執行的應用程式，您可以使用 EC2 執行個體專用的設定檔登入資料 (而非密碼) 來存取資料庫，如此安全性更高。

通常，當應用程式每秒建立的連線少於 200 個，且您不希望直接以應用程式程式碼管理使用者名稱和密碼時，請考慮使用 IAM 資料庫身分驗證。

Amazon Web Services (AWS) JDBC 驅動程式支援 IAM 資料庫身分驗證。如需詳細資訊，請參閱 [Amazon Web Services (AWS) JDBC 驅動程式 GitHub 儲存庫](https://github.com/aws/aws-advanced-jdbc-wrapper)中的 [AWS IAM 身分驗證外掛程式](https://github.com/aws/aws-advanced-jdbc-wrapper/blob/main/docs/using-the-jdbc-driver/using-plugins/UsingTheIamAuthenticationPlugin.md)。

Amazon Web Services (AWS) Python 驅動程式支援 IAM 資料庫身分驗證。如需詳細資訊，請參閱 [Amazon Web Services (AWS) Python 驅動程式 GitHub 儲存庫](https://github.com/aws/aws-advanced-python-wrapper)中的 [AWS IAM 身分驗證外掛程式](https://github.com/aws/aws-advanced-python-wrapper/blob/main/docs/using-the-python-driver/using-plugins/UsingTheIamAuthenticationPlugin.md)。

瀏覽下列主題，了解設定 IAM 進行資料庫身分驗證的程序：
+ [啟用和停用 IAM 資料庫身分驗證](UsingWithRDS.IAMDBAuth.Enabling.md)
+ [建立並使用 IAM 政策進行 IAM 資料庫存取](UsingWithRDS.IAMDBAuth.IAMPolicy.md)
+ [使用 IAM 身分驗證建立資料庫帳戶](UsingWithRDS.IAMDBAuth.DBAccounts.md)
+ [使用 IAM 身分驗證連接至資料庫執行個體](UsingWithRDS.IAMDBAuth.Connecting.md) 

## 區域和版本可用性
<a name="UsingWithRDS.IAMDBAuth.Availability"></a>

功能可用性和支援會因每個資料庫引擎的特定版本而有所不同。如需 Amazon RDS 和 IAM 資料庫身分驗證的引擎、版本和區域可用性的詳細資訊，請參閱 [支援 Amazon RDS 中 IAM 資料庫身分驗證的區域和資料庫引擎](Concepts.RDS_Fea_Regions_DB-eng.Feature.IamDatabaseAuthentication.md)。

## CLI 和開發套件支援
<a name="UsingWithRDS.IAMDBAuth.cli-sdk"></a>

IAM 資料庫身分驗證適用於 [AWS CLI](https://docs.aws.amazon.com/cli/latest/reference/rds/generate-db-auth-token.html)和下列語言特定 AWS SDKs：
+ [適用於 .NET 的 AWS SDK](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/RDS/TRDSAuthTokenGenerator.html)
+ [適用於 C\$1\$1 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/class_aws_1_1_r_d_s_1_1_r_d_s_client.html#ae134ffffed5d7672f6156d324e7bd392)
+ [適用於 Go 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-go/api/service/rds/#pkg-overview)
+ [適用於 Java 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-java/latest/reference/software/amazon/awssdk/services/rds/RdsUtilities.html)
+ [適用於 JavaScript 的 AWS SDK](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/modules/_aws_sdk_rds_signer.html)
+ [適用於 PHP 的 AWS SDK](https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.Rds.AuthTokenGenerator.html)
+ [適用於 Python (Boto3) 的 AWS SDK](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.generate_db_auth_token)
+ [適用於 Ruby 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/RDS/AuthTokenGenerator.html)

## IAM 資料庫身分驗證的限制
<a name="UsingWithRDS.IAMDBAuth.Limitations"></a>

使用 IAM 資料庫身分驗證，會套用以下限制：
+ 目前，IAM 資料庫驗證不支援所有全域條件內容金鑰。

  如需有關全域條件內容索引鍵的詳細資訊，請參閱《*IAM 使用者指南*》中的 [AWS 全域條件內容索引鍵](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html)。
+ 對於 PostgreSQL，如果 IAM 角色 (`rds_iam`) 新增至使用者 (包括 RDS 主要使用者)，則 IAM 身分驗證優先於密碼身分驗證，因此使用者必須以 IAM 使用者身分登入。
+ 對於 PostgreSQL，Amazon RDS 不支援同時啟用 IAM 和 Kerberos 身分驗證方法。
+ 對於 PostgreSQL，您無法使用 IAM 身分驗證來建立複寫連線。
+ 您無法使用自訂 Route 53 DNS 記錄，替代資料庫執行個體端點來產生身分驗證字符。
+ CloudWatch 和 CloudTrail 不會記錄 IAM 身分驗證。這些服務不會追蹤授權 IAM 角色啟用資料庫連線的 `generate-db-auth-token` API 呼叫。
+ IAM 資料庫身分驗證需要資料庫執行個體上的運算資源。您的資料庫必須擁有 300 到 1000 MiB 的額外記憶體，才能提供可靠的連線能力。若要查看工作負載所需的記憶體，請在啟用 IAM 資料庫身分驗證前後，比較增強型監控處理清單中 RDS 程序的 RES 欄。請參閱 [在 RDS 主控台中檢視作業系統指標](USER_Monitoring.OS.Viewing.md)。

  如果您使用的是爆量類別執行個體，請減少緩衝區和快取等其他參數所使用的記憶體數量，以避免記憶體不足。
+ RDS on Outposts 不支援任何引擎的 IAM 資料庫身分驗證。

## 適用於 IAM 資料庫身分驗證的建議
<a name="UsingWithRDS.IAMDBAuth.ConnectionsPerSecond"></a>

使用 IAM 資料庫身分驗證時，建議您採取以下做法：
+ 當您的應用程式每秒需要少於 200 個新的 IAM 資料庫驗證連線時，請使用 IAM 資料庫驗證。

  搭配 Amazon RDS 使用的資料庫引擎完全不限制每秒的身分驗證嘗試次數。不過，當您使用 IAM 資料庫身分驗證時，應用程式必須產生身分驗證字符。然後，應用程式會使用該字符來連接至資料庫執行個體。如果您超過每秒新連線數上限，IAM 資料庫身分驗證的額外負荷會導致連線調節。

  請考慮在應用程式中使用連線集區，以緩解持續建立連線的問題。如此可以減少 IAM 資料庫身分驗證的額外負荷，並允許您的應用程式重複使用現有連線。或者，請考慮針對這些使用案例採用 RDS Proxy。RDS Proxy需額外收費。請參閱 [RDS Proxy 定價](https://aws.amazon.com/rds/proxy/pricing/)。
+ IAM 資料庫身分驗證字符的大小取決於許多因素，包括 IAM 標籤的數量、IAM 服務政策、ARN 長度，以及其他 IAM 和資料庫屬性。此字符的最小大小一般約為 1 KB，但可以更大。因為此字符用作連線字串中的密碼，以使用 IAM 身分驗證連線至資料庫，所以您應該確保資料庫驅動程式 (例如 ODBC) 和/或任何工具不會限制或由於其大小而以其他方式截斷此字符。截斷的字符將導致資料庫和 IAM 執行的身分驗證失敗。
+ 如果您是在建立 IAM 資料庫身分驗證字符時使用臨時憑證，則在使用 IAM 資料庫身分驗證字符發出連線請求時，臨時憑證必須仍然有效。

## 不支援的 AWS 全域條件內容索引鍵
<a name="UsingWithRDS.IAMDBAuth.GlobalContextKeys"></a>

 IAM 資料庫身分驗證不支援下列 AWS 全域條件內容金鑰子集。
+ `aws:Referer`
+ `aws:SourceIp`
+ `aws:SourceVpc`
+ `aws:SourceVpce`
+ `aws:UserAgent`
+ `aws:VpcSourceIp`

如需詳細資訊，請參閱《IAM 使用者指南》**中的[AWS 全域條件內容金鑰](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html)。

# 啟用和停用 IAM 資料庫身分驗證
<a name="UsingWithRDS.IAMDBAuth.Enabling"></a>

依預設，資料庫執行個體上會停用 IAM 資料庫身分驗證。您可以使用 AWS 管理主控台 AWS CLI或 API 啟用或停用 IAM 資料庫身分驗證。

您可以在執行下列其中一個動作時啟用 IAM 資料庫身分驗證：
+ 若要建立啟用 IAM 資料庫身分驗證的新資料庫執行個體，請參閱[建立 Amazon RDS 資料庫執行個體](USER_CreateDBInstance.md)。
+ 若要修改資料庫執行個體以啟用 IAM 資料庫身分驗證，請參閱[修改 Amazon RDS 資料庫執行個體](Overview.DBInstance.Modifying.md)。
+ 如要從啟用 IAM 資料庫身分驗證的快照還原資料庫執行個體，請參閱 [還原至資料庫執行個體](USER_RestoreFromSnapshot.md)。
+ 若要在啟用 IAM 資料庫身分驗證的情況下，將資料庫執行個體叢集還原至某個時間點，請參閱[將 Amazon RDS 的資料庫執行個體還原至指定時間](USER_PIT.md)。

## 主控台
<a name="UsingWithRDS.IAMDBAuth.Enabling.Console"></a>

每個建立或修改工作流程都有一個 **Database authentication (資料庫身分驗證)** 區段，您可以在其中啟用或停用 IAM 資料庫身分驗證。在該區段中，選擇 **Password and IAM database authentication (密碼和 IAM 資料庫身分驗證)** 以啟用 IAM 資料庫身分驗證。

**為現有資料庫執行個體啟用或停用 IAM 資料庫身分驗證**

1. 前往 [https://console.aws.amazon.com/rds/](https://console.aws.amazon.com/rds/)，開啟 Amazon RDS 主控台。

1. 在導覽窗格中，選擇 **Databases** (資料庫)。

1. 選擇想要修改的資料庫執行個體。
**注意**  
 確認資料庫執行個體與 IAM 身分驗證相容。查看 [區域和版本可用性](UsingWithRDS.IAMDBAuth.md#UsingWithRDS.IAMDBAuth.Availability) 中的相容性要求。

1. 選擇 **Modify (修改)**。

1. 在**資料庫身分驗證**區段中，選擇**密碼和 IAM 資料庫身分驗證** 以啟用 IAM 資料庫身分驗證。選擇**密碼身分驗證**或**密碼和 Kerberos 身分驗證**以停用 IAM 身分驗證。

1. 您也可以選擇啟用將 IAM 資料庫身分驗證日誌發佈至 CloudWatch Logs。在**日誌匯出**下，選擇 **iam-db-auth-error 日誌**選項。將日誌發佈到 CloudWatch Logs 會消耗儲存空間，而且您需要支付該儲存空間的費用。請務必刪除您不再需要的任何 CloudWatch Logs。

1. 選擇 **Continue (繼續)**。

1. 若要立即套用變更，請在 **Scheduling of modifications (修改排程)** 區段中選擇 **Immediately (立即)**。

1. 選擇 **Modify DB instance** (修改資料庫執行個體) 。

## AWS CLI
<a name="UsingWithRDS.IAMDBAuth.Enabling.CLI"></a>

若要使用 建立具有 IAM 身分驗證的新資料庫執行個體 AWS CLI，請使用 [https://docs.aws.amazon.com/cli/latest/reference/rds/create-db-instance.html](https://docs.aws.amazon.com/cli/latest/reference/rds/create-db-instance.html)命令。指定 `--enable-iam-database-authentication` 選項，如以下範例所示。

```
aws rds create-db-instance \
    --db-instance-identifier mydbinstance \
    --db-instance-class db.m3.medium \
    --engine MySQL \
    --allocated-storage 20 \
    --master-username masterawsuser \
    --manage-master-user-password \
    --enable-iam-database-authentication
```

若要將現有資料庫執行個體更新為進行或不進行 IAM 身分驗證，請使用 AWS CLI 命令 [https://docs.aws.amazon.com/cli/latest/reference/rds/modify-db-instance.html](https://docs.aws.amazon.com/cli/latest/reference/rds/modify-db-instance.html)。視需要指定 `--enable-iam-database-authentication` 或 `--no-enable-iam-database-authentication` 選項。

**注意**  
 確認資料庫執行個體與 IAM 身分驗證相容。查看 [區域和版本可用性](UsingWithRDS.IAMDBAuth.md#UsingWithRDS.IAMDBAuth.Availability) 中的相容性要求。

依預設，Amazon RDS 會在下一次維護時段執行修改。如果您不想等待，而希望儘快啟用 IAM 資料庫身分驗證，請使用 `--apply-immediately` 參數。

以下範例示範如何對現有的資料庫執行個體立即啟用 IAM 身分驗證。

```
aws rds modify-db-instance \
    --db-instance-identifier mydbinstance \
    --apply-immediately \
    --enable-iam-database-authentication
```

如果您要還原資料庫執行個體，請使用下列其中一個 AWS CLI 命令：
+ `[restore-db-instance-to-point-in-time](https://docs.aws.amazon.com/cli/latest/reference/rds/restore-db-instance-to-point-in-time.html)`
+ `[restore-db-instance-from-db-snapshot](https://docs.aws.amazon.com/cli/latest/reference/rds/restore-db-instance-from-db-snapshot.html)`

IAM 資料庫身分驗證設定預設為來源快照的設定。若要變更此設定，請視需要設定 `--enable-iam-database-authentication` 或 `--no-enable-iam-database-authentication` 選項。

## RDS API
<a name="UsingWithRDS.IAMDBAuth.Enabling.API"></a>

若要使用 API 建立支援 IAM 身分驗證的新資料庫執行個體，請使用 API 操作 [https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_CreateDBInstance.html](https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_CreateDBInstance.html)。將 `EnableIAMDatabaseAuthentication` 參數設為 `true`。

若要更新現有資料庫執行個體進行或不進行 IAM 身分驗證，請使用 API 操作 [https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_ModifyDBInstance.html](https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_ModifyDBInstance.html)。將 `EnableIAMDatabaseAuthentication` 參數設為 `true` 以啟用 IAM 身分驗證，或設為 `false` 表示停用。

**注意**  
 確認資料庫執行個體與 IAM 身分驗證相容。查看 [區域和版本可用性](UsingWithRDS.IAMDBAuth.md#UsingWithRDS.IAMDBAuth.Availability) 中的相容性要求。

如果您要還原資料庫執行個體，請使用下列其中一個 API 操作：
+ [https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_RestoreDBInstanceFromDBSnapshot.html](https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_RestoreDBInstanceFromDBSnapshot.html)
+  [https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_RestoreDBInstanceToPointInTime.html](https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_RestoreDBInstanceToPointInTime.html)

IAM 資料庫身分驗證設定預設為來源快照的設定。若要變更此設定，請將 `EnableIAMDatabaseAuthentication` 參數設為 `true` 以啟用 IAM 身分驗證，或設為 `false` 表示停用。

# 建立並使用 IAM 政策進行 IAM 資料庫存取
<a name="UsingWithRDS.IAMDBAuth.IAMPolicy"></a>

若要允許使用者或角色連接資料庫執行個體，您必須建立 IAM 政策。然後，您可以將政策連接到許可集或角色。

**注意**  
若要進一步了解 IAM 政策，請參閱[Amazon RDS 的 Identity and access management](UsingWithRDS.IAM.md)。

以下範例政策可讓使用者利用 IAM 資料庫身分驗證來連接資料庫執行個體。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "rds-db:connect"
            ],
            "Resource": [
                "arn:aws:rds-db:us-east-2:111122223333:dbuser:db-ABCDEFGHIJKL01234/db_user"
            ]
        }
    ]
}
```

------

**重要**  
具有管理員許可的使用者可以存取資料庫執行個體，而不需 IAM 政策中的明確許可。如果您想要將管理員的存取權限制為資料庫執行個體，您可以建立具有適當、特殊權限較低的許可的 IAM 角色，並將其指派給管理員。

**注意**  
請勿混淆 `rds-db:` 前綴和其他以 `rds:` 開頭的 RDS API 操作前綴。您只能對 IAM 資料庫身分驗證使用 `rds-db:` 字首和 `rds-db:connect` 動作。它們不適用於任何其他內容。

範例政策包含單一陳述式與下列元素：
+ `Effect` – 指定 `Allow` 以授權存取資料庫執行個體。如果您未明確允許存取，預設將會拒絕存取。
+ `Action` – 指定 `rds-db:connect` 以允許連線至資料庫執行個體。
+ `Resource` – 指定 Amazon Resource Name (ARN) 以描述一個資料庫執行個體中的一個資料庫帳戶。ARN 格式如下。

  ```
  arn:aws:rds-db:region:account-id:dbuser:DbiResourceId/db-user-name
  ```

  請在此格式中更換下列項目：
  + `region` 是資料庫執行個體 AWS 的區域。在範例政策中， AWS 區域為 `us-east-2`。
  + `account-id` 是資料庫執行個體的 AWS 帳號。在此範例政策中，帳戶號碼是 `1234567890`。使用者的帳戶必須與資料庫執行個體的帳戶相同。

    若要執行跨帳户存取權，請使用資料庫執行個體帳戶中，上述的政策來建立 IAM 角色，並允許您的其他帳戶擔任該角色。
  + `DbiResourceId` 是資料庫執行個體的識別符。此識別符對 AWS 區域是唯一的，絕不會變更。在此範例政策中，識別符是 `db-ABCDEFGHIJKL01234`。

    若要在適用於 Amazon RDS AWS 管理主控台 的 中尋找資料庫執行個體資源 ID，請選擇資料庫執行個體以查看其詳細資訊。然後選擇 **Configuration (組態)** 標籤。**Resource ID (資源 ID)** 顯示在 **Configuration (組態)** 區段中。

    或者，您可以使用 AWS CLI 命令列出目前 AWS 區域中所有資料庫執行個體的識別符和資源 IDs，如下所示。

    ```
    aws rds describe-db-instances --query "DBInstances[*].[DBInstanceIdentifier,DbiResourceId]"
    ```

    若您使用的是 Amazon Aurora，請指定 `DbClusterResourceId` 而非 `DbiResourceId`。如需詳細資訊，請參閱《*Amazon Aurora 使用者指南*》中的[建立並使用 IAM 政策進行 IAM 資料庫存取](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html)。
**注意**  
如果您是透過 RDS Proxy 連線至資料庫，請指定代理資源 ID，例如 `prx-ABCDEFGHIJKL01234`。如需搭配 RDS Proxy 使用 IAM 資料庫驗證的相關資訊，請參閱[使用 IAM 身分驗證連線至資料庫](rds-proxy-connecting.md#rds-proxy-connecting-iam)。
  + `db-user-name` 是要與 IAM 身分驗證產生關聯的資料庫帳戶的名稱。在範例政策中，資料庫帳戶是 `db_user`。

您可以建構其他 ARN 來支援各種存取模式。下列政策允許存取資料庫執行個體中的兩個不同資料庫帳戶：

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
      {
         "Effect": "Allow",
         "Action": [
             "rds-db:connect"
         ],
         "Resource": [
             "arn:aws:rds-db:us-east-2:123456789012:dbuser:db-ABCDEFGHIJKL01234/jane_doe",
             "arn:aws:rds-db:us-east-2:123456789012:dbuser:db-ABCDEFGHIJKL01234/mary_roe"
         ]
      }
   ]
}
```

------

下列政策使用「\$1」字元來比對特定 AWS 帳戶和 AWS 區域的所有資料庫執行個體和資料庫帳戶。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "rds-db:connect"
            ],
            "Resource": [
                "arn:aws:rds-db:us-east-2:111122223333:dbuser:*/*"
            ]
        }
    ]
}
```

------

下列政策符合特定 AWS 帳戶和 AWS 區域的所有資料庫執行個體。不過，此政策僅授權存取具有 `jane_doe` 資料庫帳戶的資料庫執行個體。

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
      {
         "Effect": "Allow",
         "Action": [
             "rds-db:connect"
         ],
         "Resource": [
             "arn:aws:rds-db:us-east-2:123456789012:dbuser:*/jane_doe"
         ]
      }
   ]
}
```

------

使用者或角色只能存取資料庫使用者可存取的資料庫。例如，假設資料庫執行個體有一個名為 *dev* 的資料庫，還有另一個名為 *test* 的資料庫。如果資料庫使用者 `jane_doe` 只能存取 *dev*，則任何以 `jane_doe` 使用者存取該資料庫執行個體的使用者或角色，也只能存取 *dev*。其他資料庫物件同樣受此存取限制，例如資料表和檢視等。

管理員必須建立 IAM 政策，授予實體在其所需的指定資源上執行特定 API 操作的許可。管理員接著必須將這些政策連接至需要這些許可的許可集或角色。如需政策範例，請參閱 [Amazon RDS 以身分為基礎的政策範例](security_iam_id-based-policy-examples.md)。

## 將政 IAM 政策連接到許可集或角色
<a name="UsingWithRDS.IAMDBAuth.IAMPolicy.Attaching"></a>

在您建立 IAM 政策以允許資料庫身分驗證之後，您必須將該政策連接至許可集或角色。如需本主題的教學課程，請參閱《*IAM 使用者指南*》中的[建立並連接您的第一個客戶受管原則](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_managed-policies.html)。

在您進行教學課程時，可使用本節所示的其中一個政策範例做為起點，並依您的需求進行自訂。在教學課程結束時，您會有一個具有連接政策且可使用 `rds-db:connect` 動作的許可集。

**注意**  
您可以將多個許可集或角色映射至相同的資料庫使用者帳戶。例如，假設 IAM 政策指定下列資源 ARN。  

```
arn:aws:rds-db:us-east-2:123456789012:dbuser:db-12ABC34DEFG5HIJ6KLMNOP78QR/jane_doe
```
如果您將此政策連接至 *Jane*、*Bob* 和 *Diego*，則每個使用者都能使用 `jane_doe` 資料庫帳戶連線至指定的資料庫執行個體。

# 使用 IAM 身分驗證建立資料庫帳戶
<a name="UsingWithRDS.IAMDBAuth.DBAccounts"></a>

採用 IAM 資料庫身分驗證時，不需要指派資料庫密碼給您所建立的使用者帳戶。如果您移除已映射至資料庫帳戶的使用者，則應該使用 `DROP USER` 陳述式來一併移除該資料庫帳戶。

**注意**  
用於 IAM 身分驗證的使用者名稱必須與資料庫中的使用者名稱大小寫相符。

**Topics**
+ [搭配 IAM 身分驗證使用 MariaDB and MySQL](#UsingWithRDS.IAMDBAuth.DBAccounts.MySQL)
+ [搭配 PostgreSQL 使用 IAM 身分驗證](#UsingWithRDS.IAMDBAuth.DBAccounts.PostgreSQL)

## 搭配 IAM 身分驗證使用 MariaDB and MySQL
<a name="UsingWithRDS.IAMDBAuth.DBAccounts.MySQL"></a>

使用 MariaDB 和 MySQL 時，身分驗證是由 AWS處理`AWSAuthenticationPlugin`，這是與 IAM 無縫搭配運作的外掛程式，可驗證您的使用者。以主要使用者身分或可以建立使用者並授予權限的不同使用者身分連線至資料庫執行個體。連線後，發出 `CREATE USER` 陳述式，如下列範例所示。

```
CREATE USER 'jane_doe' IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS'; 
```

`IDENTIFIED WITH` 子句可讓 MariaDB and MySQL 使用 `AWSAuthenticationPlugin` 來驗證資料庫帳戶 (`jane_doe`)。`AS 'RDS'` 子句指的是身分驗證方法。確定指定的資料庫使用者名稱與 IAM 資料庫存取的 IAM 政策中的資源相同。如需詳細資訊，請參閱[建立並使用 IAM 政策進行 IAM 資料庫存取](UsingWithRDS.IAMDBAuth.IAMPolicy.md)。

**注意**  
如果您看到以下訊息，表示 AWS提供的外掛程式不適用於目前的資料庫執行個體。  
`ERROR 1524 (HY000): Plugin 'AWSAuthenticationPlugin' is not loaded`  
若要對此錯誤進行故障診斷，請確認您使用支援的組態，且已在資料庫執行個體上啟用 IAM 資料庫身分驗證。如需更多詳細資訊，請參閱 [區域和版本可用性](UsingWithRDS.IAMDBAuth.md#UsingWithRDS.IAMDBAuth.Availability) 及 [啟用和停用 IAM 資料庫身分驗證](UsingWithRDS.IAMDBAuth.Enabling.md)。

使用 `AWSAuthenticationPlugin` 建立帳戶之後，管理此帳戶的方式就像管理其他資料庫帳戶一樣。例如，您可以使用 `GRANT` 和 `REVOKE` 陳述式來修改帳戶權限，或使用 `ALTER USER` 陳述式來修改各種帳戶屬性。

使用 IAM 時，資料庫網路流量會使用 SSL/TLS 加密。若要允許 SSL 連線，請透過下列命令修改使用者帳戶。

```
ALTER USER 'jane_doe'@'%' REQUIRE SSL;     
```

 

## 搭配 PostgreSQL 使用 IAM 身分驗證
<a name="UsingWithRDS.IAMDBAuth.DBAccounts.PostgreSQL"></a>

若要搭配 PostgreSQL 使用 IAM 身分驗證，請以主要使用者身分或可以建立使用者並授予權限的不同使用者身分連線至資料庫執行個體。連線後，請建立資料庫使用者，然後將 `rds_iam` 角色授予他們，如下列範例所示。

```
CREATE USER db_userx; 
GRANT rds_iam TO db_userx;
```

確定指定的資料庫使用者名稱與 IAM 資料庫存取的 IAM 政策中的資源相同。如需詳細資訊，請參閱[建立並使用 IAM 政策進行 IAM 資料庫存取](UsingWithRDS.IAMDBAuth.IAMPolicy.md)。您必須授予 `rds_iam` 角色才能使用 IAM 身分驗證。您也可以使用巢狀成員資格或角色的間接授予。

# 使用 IAM 身分驗證連接至資料庫執行個體
<a name="UsingWithRDS.IAMDBAuth.Connecting"></a>

採用 IAM 資料庫身分驗證時，您會使用身分驗證字符來連接資料庫執行個體。*身分驗證字符*是可用來代替密碼的字元字串。產生身分驗證字符之後，過期之前的有效期限為 15 分鐘。如果您嘗試使用過期的字符來連接，則會拒絕連接請求。

每個身分驗證字符必須附帶有效的簽章，並使用 AWS 簽章第 4 版。(如需詳細資訊，請參閱 *AWS 一般參考* 中的 [Signature 第 4 版簽署程序](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html)。) AWS CLI 及 AWS SDK (例如 適用於 Java 的 AWS SDK 或 適用於 Python (Boto3) 的 AWS SDK) 可以自動簽署您建立的每個字符。

當您從另一項 AWS 服務 (例如 AWS Lambda) 連線至 Amazon RDS 時，您可以使用身分驗證字符。使用字符就可以避免將密碼寫在程式碼中。或是您可使用 AWS 開發套件，以程式設計方式建立及簽署身分驗證字符。

取得已簽署的 IAM 身分驗證字符之後，您就可以連接至 Amazon RDS 資料庫執行個體。接下來，您可以了解如何使用命令列工具或 AWS 開發套件來這樣做，例如 適用於 Java 的 AWS SDK 或 適用於 Python (Boto3) 的 AWS SDK。

如需詳細資訊，請參閱下列部落格文章：
+ [使用 IAM 身分驗證將 SQL Workbench/J 連線至 Aurora MySQL 或 Amazon RDS for MySQL](https://aws.amazon.com/blogs/database/use-iam-authentication-to-connect-with-sql-workbenchj-to-amazon-aurora-mysql-or-amazon-rds-for-mysql/)
+ [Using IAM authentication to connect with pgAdmin Amazon Aurora PostgreSQL or Amazon RDS for PostgreSQL](https://aws.amazon.com/blogs/database/using-iam-authentication-to-connect-with-pgadmin-amazon-aurora-postgresql-or-amazon-rds-for-postgresql/)

**先決條件**  
以下是使用 IAM 身分驗證連線至資料庫執行個體的先決條件：
+ [啟用和停用 IAM 資料庫身分驗證](UsingWithRDS.IAMDBAuth.Enabling.md)
+ [建立並使用 IAM 政策進行 IAM 資料庫存取](UsingWithRDS.IAMDBAuth.IAMPolicy.md)
+ [使用 IAM 身分驗證建立資料庫帳戶](UsingWithRDS.IAMDBAuth.DBAccounts.md)

**Topics**
+ [使用 IAM 身分驗證和 AWS 驅動程式連線至資料庫執行個體](IAMDBAuth.Connecting.Drivers.md)
+ [從命令列 AWS CLI 和 mysql 用戶端使用 IAM 身分驗證連線至資料庫執行個體](UsingWithRDS.IAMDBAuth.Connecting.AWSCLI.md)
+ [從命令列： AWS CLI 和 psql 用戶端使用 IAM 身分驗證連線至資料庫執行個體](UsingWithRDS.IAMDBAuth.Connecting.AWSCLI.PostgreSQL.md)
+ [使用 IAM 身分驗證和 連線至資料庫執行個體 適用於 .NET 的 AWS SDK](UsingWithRDS.IAMDBAuth.Connecting.NET.md)
+ [使用 IAM 身分驗證和 連線至資料庫執行個體 適用於 Go 的 AWS SDK](UsingWithRDS.IAMDBAuth.Connecting.Go.md)
+ [使用 IAM 身分驗證和 連線至資料庫執行個體 適用於 Java 的 AWS SDK](UsingWithRDS.IAMDBAuth.Connecting.Java.md)
+ [使用 IAM 身分驗證和 連線至資料庫執行個體 適用於 Python (Boto3) 的 AWS SDK](UsingWithRDS.IAMDBAuth.Connecting.Python.md)

# 使用 IAM 身分驗證和 AWS 驅動程式連線至資料庫執行個體
<a name="IAMDBAuth.Connecting.Drivers"></a>

驅動程式AWS套件旨在支援更快的切換和容錯移轉時間，以及使用 AWS Secrets Manager、 AWS Identity and Access Management(IAM) 和聯合身分進行身分驗證。AWS 驅動程式依賴監控資料庫執行個體狀態，並注意執行個體拓撲以判斷新的寫入器。相較於開放原始碼驅動程式的數十秒，此方法可將切換和容錯移轉時間縮短為短短幾秒。

如需 AWS 驅動程式的詳細資訊，請參閱 [RDS for MariaDB](MariaDB.Connecting.Drivers.md#MariaDB.Connecting.JDBCDriver)、[RDS for MySQL](MySQL.Connecting.Drivers.md#MySQL.Connecting.JDBCDriver) 或 [RDS for PostgreSQL](PostgreSQL.Connecting.JDBCDriver.md) 資料庫執行個體的對應語言驅動程式。

**注意**  
RDS for MariaDB 支援的唯一功能是使用 AWS Secrets Manager、AWS Identity and Access Management (IAM) 和聯合身分進行身分驗證。

# 從命令列 AWS CLI 和 mysql 用戶端使用 IAM 身分驗證連線至資料庫執行個體
<a name="UsingWithRDS.IAMDBAuth.Connecting.AWSCLI"></a>

您可以使用 AWS CLI 和 `mysql`命令列工具，從命令列連線至 Amazon RDS 資料庫執行個體，如下所述。

**先決條件**  
以下是使用 IAM 身分驗證連線至資料庫執行個體的先決條件：
+ [啟用和停用 IAM 資料庫身分驗證](UsingWithRDS.IAMDBAuth.Enabling.md)
+ [建立並使用 IAM 政策進行 IAM 資料庫存取](UsingWithRDS.IAMDBAuth.IAMPolicy.md)
+ [使用 IAM 身分驗證建立資料庫帳戶](UsingWithRDS.IAMDBAuth.DBAccounts.md)

**注意**  
有關使用 SQL Workbench/J 與 IAM 身分驗證連接到您的資料庫的資訊，請參閱部落格文章 [使用 IAM 身分驗證將 SQL Workbench/J 連線至 Aurora MySQL 或 Amazon RDS for MySQL](https://aws.amazon.com/blogs/database/use-iam-authentication-to-connect-with-sql-workbenchj-to-amazon-aurora-mysql-or-amazon-rds-for-mysql/)。

**Topics**
+ [產生 IAM 身分驗證字符](#UsingWithRDS.IAMDBAuth.Connecting.AWSCLI.AuthToken)
+ [連接至資料庫執行個體](#UsingWithRDS.IAMDBAuth.Connecting.AWSCLI.Connect)

## 產生 IAM 身分驗證字符
<a name="UsingWithRDS.IAMDBAuth.Connecting.AWSCLI.AuthToken"></a>

以下範例顯示如何使用 AWS CLI來取得已簽署的身分驗證字符。

```
aws rds generate-db-auth-token \
   --hostname rdsmysql.123456789012.us-west-2.rds.amazonaws.com \
   --port 3306 \
   --region us-west-2 \
   --username jane_doe
```

範例中的參數如下：
+ `--hostname` – 您想要存取之資料庫執行個體的主機名稱
+ `--port` – 用於連線資料庫執行個體的連接埠號碼
+ `--region` – 資料庫執行個體執行所在的 AWS 區域
+ `--username` – 您想要存取的資料庫帳戶

字符開頭的前幾個字元看起來如下所示。

```
rdsmysql.123456789012.us-west-2.rds.amazonaws.com:3306/?Action=connect&DBUser=jane_doe&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Expires=900...
```

**注意**  
您無法使用自訂 Route 53 DNS 記錄，替代資料庫執行個體端點來產生身分驗證字符。

## 連接至資料庫執行個體
<a name="UsingWithRDS.IAMDBAuth.Connecting.AWSCLI.Connect"></a>

連線的一般格式如下所示。

```
mysql --host=hostName --port=portNumber --ssl-ca=full_path_to_ssl_certificate --enable-cleartext-plugin --user=userName --password=authToken
```

參數如下：
+ `--host` – 您想要存取之資料庫執行個體的主機名稱
+ `--port` – 用於連線資料庫執行個體的連接埠號碼
+ `--ssl-ca` – 包含公有金鑰之 SSL 憑證檔案的完整路徑

  如需 SSL/TLS 支援 MariaDB 的詳細資訊，請參閱 [Amazon RDS 支援在 MariaDB 資料庫執行個體上啟用 SSL/TLS 加密。](MariaDB.Concepts.SSLSupport.md)。

  如需 SSL/TLS 支援 MySQL 的詳細資訊，請參閱 [Amazon RDS 對 MySQL 資料庫執行個體的 SSL/TLS 支援](MySQL.Concepts.SSLSupport.md)。

  若要下載 SSL 憑證，請參閱[使用 SSL/TLS 加密與資料庫執行個體或叢集的連線](UsingWithRDS.SSL.md)。
+ `--enable-cleartext-plugin` – 指定 `AWSAuthenticationPlugin` 必須用於此連線的值

  如果您使用的是 MariaDB 用戶端，該 `--enable-cleartext-plugin` 選項不是必需的。
+ `--user` – 您想要存取的資料庫帳戶
+ `--password` – 已簽署的 IAM 身分驗證字符

身分驗證字符由數百個字元組成。在命令列上可能會顯得雜亂。此問題的一個解決方法是將字符儲存到環境變數，然後在連接時使用該變數。以下範例顯示此解決方法的一種型態。在範例中，*/sample\$1dir/* 是包含公有金鑰之 SSL 憑證檔案的完整路徑。

```
RDSHOST="mysqldb.123456789012.us-east-1.rds.amazonaws.com"
TOKEN="$(aws rds generate-db-auth-token --hostname $RDSHOST --port 3306 --region us-west-2 --username jane_doe )"

mysql --host=$RDSHOST --port=3306 --ssl-ca=/sample_dir/global-bundle.pem --enable-cleartext-plugin --user=jane_doe --password=$TOKEN
```

使用 `AWSAuthenticationPlugin` 來連接時會以 SSL 保護連線。若要確認是否如此，請在 `mysql>` 命令提示中輸入下列命令。

```
show status like 'Ssl%';
```

輸出中的以下幾行顯示更多詳細資訊。

```
+---------------+-------------+
| Variable_name | Value                                                                                                                                                                                                                                |
+---------------+-------------+
| ...           | ...
| Ssl_cipher    | AES256-SHA                                                                                                                                                                                                                           |
| ...           | ...
| Ssl_version   | TLSv1.1                                                                                                                                                                                                                              |
| ...           | ...
+-----------------------------+
```

如果要透過 Proxy 連線到資料庫執行個體，請參閱 [使用 IAM 身分驗證連線至資料庫](rds-proxy-connecting.md#rds-proxy-connecting-iam)。

# 從命令列： AWS CLI 和 psql 用戶端使用 IAM 身分驗證連線至資料庫執行個體
<a name="UsingWithRDS.IAMDBAuth.Connecting.AWSCLI.PostgreSQL"></a>

您可以使用 AWS CLI 和 psql 命令列工具，從命令列連線至 Amazon RDS for PostgreSQL 資料庫執行個體，如下所述。

**先決條件**  
以下是使用 IAM 身分驗證連線至資料庫執行個體的先決條件：
+ [啟用和停用 IAM 資料庫身分驗證](UsingWithRDS.IAMDBAuth.Enabling.md)
+ [建立並使用 IAM 政策進行 IAM 資料庫存取](UsingWithRDS.IAMDBAuth.IAMPolicy.md)
+ [使用 IAM 身分驗證建立資料庫帳戶](UsingWithRDS.IAMDBAuth.DBAccounts.md)

**注意**  
如需有關使用 pgAdmin 搭配 IAM 身分驗證連線到資料庫的資訊，請參閱部落格文章 [使用 IAM 身分驗證與 pgAdmin Amazon Aurora PostgreSQL 或 Amazon RDS for PostgreSQL](https://aws.amazon.com/blogs/database/using-iam-authentication-to-connect-with-pgadmin-amazon-aurora-postgresql-or-amazon-rds-for-postgresql/) 連線。

**Topics**
+ [產生 IAM 身分驗證字符](#UsingWithRDS.IAMDBAuth.Connecting.AWSCLI.AuthToken.PostgreSQL)
+ [連接至 Amazon RDS PostgreSQL 執行個體](#UsingWithRDS.IAMDBAuth.Connecting.AWSCLI.Connect.PostgreSQL)

## 產生 IAM 身分驗證字符
<a name="UsingWithRDS.IAMDBAuth.Connecting.AWSCLI.AuthToken.PostgreSQL"></a>

身分驗證字符由數百個字元組成，因此在命令列上可能會顯得雜亂。此問題的一個解決方法是將字符儲存到環境變數，然後在連接時使用該變數。下列範例示範如何使用 AWS CLI 來取得使用 `generate-db-auth-token`命令簽署的身分驗證字符，並將其存放在`PGPASSWORD`環境變數中。

```
export RDSHOST="rdspostgres.123456789012.us-west-2.rds.amazonaws.com"
export PGPASSWORD="$(aws rds generate-db-auth-token --hostname $RDSHOST --port 5432 --region us-west-2 --username jane_doe )"
```

在範例中，`generate-db-auth-token` 命令的參數如下所示：
+ `--hostname` – 您想要存取之資料庫執行個體的主機名稱
+ `--port` – 用於連線資料庫執行個體的連接埠號碼
+ `--region` – 資料庫執行個體執行所在的 AWS 區域
+ `--username` – 您想要存取的資料庫帳戶

所產生字符開頭的前幾個字元看起來如下所示。

```
rdspostgres.123456789012.us-west-2.rds.amazonaws.com:5432/?Action=connect&DBUser=jane_doe&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Expires=900...
```

**注意**  
您無法使用自訂 Route 53 DNS 記錄，替代資料庫執行個體端點來產生身分驗證字符。

## 連接至 Amazon RDS PostgreSQL 執行個體
<a name="UsingWithRDS.IAMDBAuth.Connecting.AWSCLI.Connect.PostgreSQL"></a>

使用 psql 連線的一般格式如下所示。

```
psql "host=hostName port=portNumber sslmode=verify-full sslrootcert=full_path_to_ssl_certificate dbname=DBName user=userName password=authToken"
```

參數如下：
+ `host` – 您想要存取之資料庫執行個體的主機名稱
+ `port` – 用於連線資料庫執行個體的連接埠號碼
+ `sslmode` – 要使用的 SSL 模式

  當您使用 `sslmode=verify-full` 時，SSL 連線會根據 SSL 憑證中的端點來驗證資料庫執行個體端點。
+ `sslrootcert` – 包含公有金鑰之 SSL 憑證檔案的完整路徑

  如需詳細資訊，請參閱[將 SSL 與 PostgreSQL 資料庫執行個體搭配使用](PostgreSQL.Concepts.General.SSL.md)。

  若要下載 SSL 憑證，請參閱[使用 SSL/TLS 加密與資料庫執行個體或叢集的連線](UsingWithRDS.SSL.md)。
+ `dbname` – 您想要存取的資料庫
+ `user` – 您想要存取的資料庫帳戶
+ `password` – 已簽署的 IAM 身分驗證字符

**注意**  
您無法使用自訂 Route 53 DNS 記錄，替代資料庫執行個體端點來產生身分驗證字符。

以下範例示範使用 psql 進行連線。在範例中，psql 針對主機使用環境變數 `RDSHOST`，產生的字符則使用環境變數 `PGPASSWORD`。此外，*/sample\$1dir/* 是包含公有金鑰之 SSL 憑證檔案的完整路徑。

```
export RDSHOST="rdspostgres.123456789012.us-west-2.rds.amazonaws.com"
export PGPASSWORD="$(aws rds generate-db-auth-token --hostname $RDSHOST --port 5432 --region us-west-2 --username jane_doe )"
                    
psql "host=$RDSHOST port=5432 sslmode=verify-full sslrootcert=/sample_dir/global-bundle.pem dbname=DBName user=jane_doe password=$PGPASSWORD"
```

如果要透過 Proxy 連線到資料庫執行個體，請參閱 [使用 IAM 身分驗證連線至資料庫](rds-proxy-connecting.md#rds-proxy-connecting-iam)。

# 使用 IAM 身分驗證和 連線至資料庫執行個體 適用於 .NET 的 AWS SDK
<a name="UsingWithRDS.IAMDBAuth.Connecting.NET"></a>

您可以使用 連線到 RDS for MariaDB、MySQL 或 PostgreSQL 資料庫執行個體 適用於 .NET 的 AWS SDK ，如下所述。

**先決條件**  
以下是使用 IAM 身分驗證連線至資料庫執行個體的先決條件：
+ [啟用和停用 IAM 資料庫身分驗證](UsingWithRDS.IAMDBAuth.Enabling.md)
+ [建立並使用 IAM 政策進行 IAM 資料庫存取](UsingWithRDS.IAMDBAuth.IAMPolicy.md)
+ [使用 IAM 身分驗證建立資料庫帳戶](UsingWithRDS.IAMDBAuth.DBAccounts.md)

**範例**  
以下程式碼範例顯示如何產生身分驗證字符，然後用來連線至資料庫執行個體。

若要執行此程式碼範例，您需要在 AWS 網站上[適用於 .NET 的 AWS SDK](https://aws.amazon.com/sdk-for-net/)找到的 。`AWSSDK.CORE` 和 `AWSSDK.RDS` 套件是必需的。若要連接到資料庫執行個體，請使用資料庫引擎的 .NET 資料庫連接器，例如 MariaDB 或 MySQL 的 MySqlConnector 或 PostgreSQL 的 Npgsql。

此程式碼連接到 MariaDB 或 MySQL 資料庫執行個體。視需要修改下列變數的值：
+ `server` – 您想要存取之資料庫執行個體的端點
+ `user` – 您想要存取的資料庫帳戶
+ `database` – 您想要存取的資料庫
+ `port` – 用於連線資料庫執行個體的連接埠號碼
+ `SslMode` – 要使用的 SSL 模式

  當您使用 `SslMode=Required` 時，SSL 連線會根據 SSL 憑證中的端點來驗證資料庫執行個體端點。
+ `SslCa` – Amazon RDS 之 SSL 憑證的完整路徑

  若要下載憑證，請參閱[使用 SSL/TLS 加密與資料庫執行個體或叢集的連線](UsingWithRDS.SSL.md)。

**注意**  
您無法使用自訂 Route 53 DNS 記錄，替代資料庫執行個體端點來產生身分驗證字符。

```
using System;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
using Amazon;

namespace ubuntu
{
  class Program
  {
    static void Main(string[] args)
    {
      var pwd = Amazon.RDS.Util.RDSAuthTokenGenerator.GenerateAuthToken(RegionEndpoint.USEast1, "mysqldb.123456789012.us-east-1.rds.amazonaws.com", 3306, "jane_doe");
      // for debug only Console.Write("{0}\n", pwd);  //this verifies the token is generated

      MySqlConnection conn = new MySqlConnection($"server=mysqldb.123456789012.us-east-1.rds.amazonaws.com;user=jane_doe;database=mydB;port=3306;password={pwd};SslMode=Required;SslCa=full_path_to_ssl_certificate");
      conn.Open();

      // Define a query
      MySqlCommand sampleCommand = new MySqlCommand("SHOW DATABASES;", conn);

      // Execute a query
      MySqlDataReader mysqlDataRdr = sampleCommand.ExecuteReader();

      // Read all rows and output the first column in each row
      while (mysqlDataRdr.Read())
        Console.WriteLine(mysqlDataRdr[0]);

      mysqlDataRdr.Close();
      // Close connection
      conn.Close();
    }
  }
}
```

此程式碼會連線至 PostgreSQL 資料庫執行個體。

視需要修改下列變數的值：
+ `Server` – 您想要存取之資料庫執行個體的端點
+ `User ID` – 您想要存取的資料庫帳戶
+ `Database` – 您想要存取的資料庫
+ `Port` – 用於連線資料庫執行個體的連接埠號碼
+ `SSL Mode` – 要使用的 SSL 模式

  當您使用 `SSL Mode=Required` 時，SSL 連線會根據 SSL 憑證中的端點來驗證資料庫執行個體端點。
+ `Root Certificate` – Amazon RDS 之 SSL 憑證的完整路徑

  若要下載憑證，請參閱[使用 SSL/TLS 加密與資料庫執行個體或叢集的連線](UsingWithRDS.SSL.md)。

**注意**  
您無法使用自訂 Route 53 DNS 記錄，替代資料庫執行個體端點來產生身分驗證字符。

```
using System;
using Npgsql;
using Amazon.RDS.Util;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var pwd = RDSAuthTokenGenerator.GenerateAuthToken("postgresmydb.123456789012.us-east-1.rds.amazonaws.com", 5432, "jane_doe");
// for debug only Console.Write("{0}\n", pwd);  //this verifies the token is generated

            NpgsqlConnection conn = new NpgsqlConnection($"Server=postgresmydb.123456789012.us-east-1.rds.amazonaws.com;User Id=jane_doe;Password={pwd};Database=mydb;SSL Mode=Require;Root Certificate=full_path_to_ssl_certificate");
            conn.Open();

            // Define a query
                   NpgsqlCommand cmd = new NpgsqlCommand("select count(*) FROM pg_user", conn);

            // Execute a query
            NpgsqlDataReader dr = cmd.ExecuteReader();

            // Read all rows and output the first column in each row
            while (dr.Read())
                Console.Write("{0}\n", dr[0]);

            // Close connection
            conn.Close();
        }
    }
}
```

如果要透過 Proxy 連線到資料庫執行個體，請參閱 [使用 IAM 身分驗證連線至資料庫](rds-proxy-connecting.md#rds-proxy-connecting-iam)。

# 使用 IAM 身分驗證和 連線至資料庫執行個體 適用於 Go 的 AWS SDK
<a name="UsingWithRDS.IAMDBAuth.Connecting.Go"></a>

您可以使用 連線到 RDS for MariaDB、MySQL 或 PostgreSQL 資料庫執行個體 適用於 Go 的 AWS SDK ，如下所述。

**先決條件**  
以下是使用 IAM 身分驗證連線至資料庫執行個體的先決條件：
+ [啟用和停用 IAM 資料庫身分驗證](UsingWithRDS.IAMDBAuth.Enabling.md)
+ [建立並使用 IAM 政策進行 IAM 資料庫存取](UsingWithRDS.IAMDBAuth.IAMPolicy.md)
+ [使用 IAM 身分驗證建立資料庫帳戶](UsingWithRDS.IAMDBAuth.DBAccounts.md)

**範例**  
若要執行這些程式碼範例，您需要在 AWS 網站上[適用於 Go 的 AWS SDK](https://aws.amazon.com/sdk-for-go/)找到的 。

視需要修改下列變數的值：
+ `dbName` – 您想要存取的資料庫
+ `dbUser` – 您想要存取的資料庫帳戶
+ `dbHost` – 您想要存取之資料庫執行個體的端點
**注意**  
您無法使用自訂 Route 53 DNS 記錄，替代資料庫執行個體端點來產生身分驗證字符。
+ `dbPort` – 用於連線資料庫執行個體的連接埠號碼
+ `region` – 資料庫執行個體執行所在的 AWS 區域

此外，請確定範例程式碼中匯入的程式庫存在於您的系統上。

**重要**  
本節中的範例使用下列程式碼來提供從本機環境存取資料庫的登入資料：  
`creds := credentials.NewEnvCredentials()`  
如果您從 AWS 服務存取資料庫，例如 Amazon EC2 或 Amazon ECS，您可以將程式碼取代為下列程式碼：  
`sess := session.Must(session.NewSession())`  
`creds := sess.Config.Credentials`  
如果您進行此變更，請確定您新增了下列匯入：  
`"github.com/aws/aws-sdk-go/aws/session"`

**Topics**
+ [使用 IAM 身分驗證和 適用於 Go 的 AWS SDK V2 進行連線](#UsingWithRDS.IAMDBAuth.Connecting.GoV2)
+ [使用 IAM 身分驗證和 適用於 Go 的 AWS SDK V1 進行連線。](#UsingWithRDS.IAMDBAuth.Connecting.GoV1)

## 使用 IAM 身分驗證和 適用於 Go 的 AWS SDK V2 進行連線
<a name="UsingWithRDS.IAMDBAuth.Connecting.GoV2"></a>

您可以使用 IAM 身分驗證和 適用於 Go 的 AWS SDK V2 連線到資料庫執行個體。

以下程式碼範例顯示如何產生身分驗證字符，然後用來連線至資料庫執行個體。

此程式碼連接到 MariaDB 或 MySQL 資料庫執行個體。

```
package main
                
import (
     "context"
     "database/sql"
     "fmt"

     "github.com/aws/aws-sdk-go-v2/config"
     "github.com/aws/aws-sdk-go-v2/feature/rds/auth"
     _ "github.com/go-sql-driver/mysql"
)

func main() {

     var dbName string = "DatabaseName"
     var dbUser string = "DatabaseUser"
     var dbHost string = "mysqldb.123456789012.us-east-1.rds.amazonaws.com"
     var dbPort int = 3306
     var dbEndpoint string = fmt.Sprintf("%s:%d", dbHost, dbPort)
     var region string = "us-east-1"

    cfg, err := config.LoadDefaultConfig(context.TODO())
    if err != nil {
    	panic("configuration error: " + err.Error())
    }

    authenticationToken, err := auth.BuildAuthToken(
    	context.TODO(), dbEndpoint, region, dbUser, cfg.Credentials)
    if err != nil {
	    panic("failed to create authentication token: " + err.Error())
    }

    dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?tls=true&allowCleartextPasswords=true",
        dbUser, authenticationToken, dbEndpoint, dbName,
    )

    db, err := sql.Open("mysql", dsn)
    if err != nil {
        panic(err)
    }

    err = db.Ping()
    if err != nil {
        panic(err)
    }
}
```

此程式碼會連線至 PostgreSQL 資料庫執行個體。

```
package main

import (
     "context"
     "database/sql"
     "fmt"

     "github.com/aws/aws-sdk-go-v2/config"
     "github.com/aws/aws-sdk-go-v2/feature/rds/auth"
     _ "github.com/lib/pq"
)

func main() {

     var dbName string = "DatabaseName"
     var dbUser string = "DatabaseUser"
     var dbHost string = "postgresmydb.123456789012.us-east-1.rds.amazonaws.com"
     var dbPort int = 5432
     var dbEndpoint string = fmt.Sprintf("%s:%d", dbHost, dbPort)
     var region string = "us-east-1"

    cfg, err := config.LoadDefaultConfig(context.TODO())
    if err != nil {
    	panic("configuration error: " + err.Error())
    }

    authenticationToken, err := auth.BuildAuthToken(
    	context.TODO(), dbEndpoint, region, dbUser, cfg.Credentials)
    if err != nil {
	    panic("failed to create authentication token: " + err.Error())
    }

    dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s",
        dbHost, dbPort, dbUser, authenticationToken, dbName,
    )

    db, err := sql.Open("postgres", dsn)
    if err != nil {
        panic(err)
    }

    err = db.Ping()
    if err != nil {
        panic(err)
    }
}
```

如果要透過 Proxy 連線到資料庫執行個體，請參閱 [使用 IAM 身分驗證連線至資料庫](rds-proxy-connecting.md#rds-proxy-connecting-iam)。

## 使用 IAM 身分驗證和 適用於 Go 的 AWS SDK V1 進行連線。
<a name="UsingWithRDS.IAMDBAuth.Connecting.GoV1"></a>

您可以使用 IAM 身分驗證和 適用於 Go 的 AWS SDK V1 連線到資料庫執行個體 

以下程式碼範例顯示如何產生身分驗證字符，然後用來連線至資料庫執行個體。

此程式碼連接到 MariaDB 或 MySQL 資料庫執行個體。

```
package main
         
import (
    "database/sql"
    "fmt"
    "log"

    "github.com/aws/aws-sdk-go/aws/credentials"
    "github.com/aws/aws-sdk-go/service/rds/rdsutils"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    dbName := "app"
    dbUser := "jane_doe"
    dbHost := "mysqldb.123456789012.us-east-1.rds.amazonaws.com"
    dbPort := 3306
    dbEndpoint := fmt.Sprintf("%s:%d", dbHost, dbPort)
    region := "us-east-1"

    creds := credentials.NewEnvCredentials()
    authToken, err := rdsutils.BuildAuthToken(dbEndpoint, region, dbUser, creds)
    if err != nil {
        panic(err)
    }

    dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?tls=true&allowCleartextPasswords=true",
        dbUser, authToken, dbEndpoint, dbName,
    )

    db, err := sql.Open("mysql", dsn)
    if err != nil {
        panic(err)
    }

    err = db.Ping()
    if err != nil {
        panic(err)
    }
}
```

此程式碼會連線至 PostgreSQL 資料庫執行個體。

```
package main

import (
	"database/sql"
	"fmt"

	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/service/rds/rdsutils"
	_ "github.com/lib/pq"
)

func main() {
    dbName := "app"
    dbUser := "jane_doe"
    dbHost := "postgresmydb.123456789012.us-east-1.rds.amazonaws.com"
    dbPort := 5432
    dbEndpoint := fmt.Sprintf("%s:%d", dbHost, dbPort)
    region := "us-east-1"

    creds := credentials.NewEnvCredentials()
    authToken, err := rdsutils.BuildAuthToken(dbEndpoint, region, dbUser, creds)
    if err != nil {
        panic(err)
    }

    dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s",
        dbHost, dbPort, dbUser, authToken, dbName,
    )

    db, err := sql.Open("postgres", dsn)
    if err != nil {
        panic(err)
    }

    err = db.Ping()
    if err != nil {
        panic(err)
    }
}
```

如果要透過 Proxy 連線到資料庫執行個體，請參閱 [使用 IAM 身分驗證連線至資料庫](rds-proxy-connecting.md#rds-proxy-connecting-iam)。

# 使用 IAM 身分驗證和 連線至資料庫執行個體 適用於 Java 的 AWS SDK
<a name="UsingWithRDS.IAMDBAuth.Connecting.Java"></a>

您可以使用 連線到 RDS for MariaDB、MySQL 或 PostgreSQL 資料庫執行個體 適用於 Java 的 AWS SDK ，如下所述。

**先決條件**  
以下是使用 IAM 身分驗證連線至資料庫執行個體的先決條件：
+ [啟用和停用 IAM 資料庫身分驗證](UsingWithRDS.IAMDBAuth.Enabling.md)
+ [建立並使用 IAM 政策進行 IAM 資料庫存取](UsingWithRDS.IAMDBAuth.IAMPolicy.md)
+ [使用 IAM 身分驗證建立資料庫帳戶](UsingWithRDS.IAMDBAuth.DBAccounts.md)
+ [設定適用於 Java 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-install.html)

如需如何使用 SDK for Java 2.x 的範例，請參閱[使用 SDK for Java 2.x 的 Amazon RDS 範例](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/java_rds_code_examples.html)。您也可以使用 AWS 進階 JDBC 包裝函式，請參閱[AWS 進階 JDBC 包裝函式文件](https://github.com/aws/aws-advanced-jdbc-wrapper/blob/main/docs/Documentation.md)。

**Topics**
+ [產生 IAM 身分驗證字符](#UsingWithRDS.IAMDBAuth.Connecting.Java.AuthToken)
+ [手動建構 IAM 身分驗證字符](#UsingWithRDS.IAMDBAuth.Connecting.Java.AuthToken2)
+ [連接至資料庫執行個體](#UsingWithRDS.IAMDBAuth.Connecting.Java.AuthToken.Connect)

## 產生 IAM 身分驗證字符
<a name="UsingWithRDS.IAMDBAuth.Connecting.Java.AuthToken"></a>

如果您使用 撰寫程式 適用於 Java 的 AWS SDK，您可以使用 `RdsIamAuthTokenGenerator`類別取得已簽署的身分驗證字符。使用此類別需要您提供 AWS 登入資料。若要這樣做，您可以建立 `DefaultAWSCredentialsProviderChain`類別的執行個體。 `DefaultAWSCredentialsProviderChain`會使用其在[預設登入資料提供者鏈](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html#credentials-default)中找到的第一個 AWS 存取金鑰和私密金鑰。如需有關 AWS 存取金鑰的詳細資訊，請參閱[管理使用者的存取金鑰](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)。

**注意**  
您無法使用自訂 Route 53 DNS 記錄，替代資料庫執行個體端點來產生身分驗證字符。

建立 `RdsIamAuthTokenGenerator` 的執行個體之後，您可以呼叫 `getAuthToken` 方法來取得已簽署的字符。提供 AWS 區域、主機名稱、連接埠名稱和使用者名稱。以下程式碼範例示範如何執行此作業。

```
package com.amazonaws.codesamples;

import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.rds.auth.GetIamAuthTokenRequest;
import com.amazonaws.services.rds.auth.RdsIamAuthTokenGenerator;

public class GenerateRDSAuthToken {

    public static void main(String[] args) {

	    String region = "us-west-2";
	    String hostname = "rdsmysql.123456789012.us-west-2.rds.amazonaws.com";
	    String port = "3306";
	    String username = "jane_doe";
	
	    System.out.println(generateAuthToken(region, hostname, port, username));
    }

    static String generateAuthToken(String region, String hostName, String port, String username) {

	    RdsIamAuthTokenGenerator generator = RdsIamAuthTokenGenerator.builder()
		    .credentials(new DefaultAWSCredentialsProviderChain())
		    .region(region)
		    .build();

	    String authToken = generator.getAuthToken(
		    GetIamAuthTokenRequest.builder()
		    .hostname(hostName)
		    .port(Integer.parseInt(port))
		    .userName(username)
		    .build());
	    
	    return authToken;
    }

}
```

## 手動建構 IAM 身分驗證字符
<a name="UsingWithRDS.IAMDBAuth.Connecting.Java.AuthToken2"></a>

在 Java 中，產生身分驗證字符最簡單的方式就是使用 `RdsIamAuthTokenGenerator`。此類別會為您建立身分驗證字符，然後使用 AWS 簽章第 4 版進行簽署。如需詳細資訊，請參閱 *AWS 一般參考* 中的 [Signature 第 4 版簽署程序](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html)。

不過，您也可以手動建構和簽署身分驗證字符，如下列程式碼範例所示。

```
package com.amazonaws.codesamples;

import com.amazonaws.SdkClientException;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.auth.SigningAlgorithm;
import com.amazonaws.util.BinaryUtils;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SortedMap;
import java.util.TreeMap;

import static com.amazonaws.auth.internal.SignerConstants.AWS4_TERMINATOR;
import static com.amazonaws.util.StringUtils.UTF8;

public class CreateRDSAuthTokenManually {
    public static String httpMethod = "GET";
    public static String action = "connect";
    public static String canonicalURIParameter = "/";
    public static SortedMap<String, String> canonicalQueryParameters = new TreeMap();
    public static String payload = StringUtils.EMPTY;
    public static String signedHeader = "host";
    public static String algorithm = "AWS4-HMAC-SHA256";
    public static String serviceName = "rds-db";
    public static String requestWithoutSignature;

    public static void main(String[] args) throws Exception {

        String region = "us-west-2";
        String instanceName = "rdsmysql.123456789012.us-west-2.rds.amazonaws.com";
        String port = "3306";
        String username = "jane_doe";
	
        Date now = new Date();
        String date = new SimpleDateFormat("yyyyMMdd").format(now);
        String dateTimeStamp = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'").format(now);
        DefaultAWSCredentialsProviderChain creds = new DefaultAWSCredentialsProviderChain();
	    String awsAccessKey = creds.getCredentials().getAWSAccessKeyId();
	    String awsSecretKey = creds.getCredentials().getAWSSecretKey();
        String expiryMinutes = "900";
        
        System.out.println("Step 1:  Create a canonical request:");
        String canonicalString = createCanonicalString(username, awsAccessKey, date, dateTimeStamp, region, expiryMinutes, instanceName, port);
        System.out.println(canonicalString);
        System.out.println();

        System.out.println("Step 2:  Create a string to sign:");        
        String stringToSign = createStringToSign(dateTimeStamp, canonicalString, awsAccessKey, date, region);
        System.out.println(stringToSign);
        System.out.println();

        System.out.println("Step 3:  Calculate the signature:");        
        String signature = BinaryUtils.toHex(calculateSignature(stringToSign, newSigningKey(awsSecretKey, date, region, serviceName)));
        System.out.println(signature);
        System.out.println();

        System.out.println("Step 4:  Add the signing info to the request");                
        System.out.println(appendSignature(signature));
        System.out.println();
        
    }

    //Step 1: Create a canonical request date should be in format YYYYMMDD and dateTime should be in format YYYYMMDDTHHMMSSZ
    public static String createCanonicalString(String user, String accessKey, String date, String dateTime, String region, String expiryPeriod, String hostName, String port) throws Exception {
        canonicalQueryParameters.put("Action", action);
        canonicalQueryParameters.put("DBUser", user);
        canonicalQueryParameters.put("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
        canonicalQueryParameters.put("X-Amz-Credential", accessKey + "%2F" + date + "%2F" + region + "%2F" + serviceName + "%2Faws4_request");
        canonicalQueryParameters.put("X-Amz-Date", dateTime);
        canonicalQueryParameters.put("X-Amz-Expires", expiryPeriod);
        canonicalQueryParameters.put("X-Amz-SignedHeaders", signedHeader);
        String canonicalQueryString = "";
        while(!canonicalQueryParameters.isEmpty()) {
            String currentQueryParameter = canonicalQueryParameters.firstKey();
            String currentQueryParameterValue = canonicalQueryParameters.remove(currentQueryParameter);
            canonicalQueryString = canonicalQueryString + currentQueryParameter + "=" + currentQueryParameterValue;
            if (!currentQueryParameter.equals("X-Amz-SignedHeaders")) {
                canonicalQueryString += "&";
            }
        }
        String canonicalHeaders = "host:" + hostName + ":" + port + '\n';
        requestWithoutSignature = hostName + ":" + port + "/?" + canonicalQueryString;

        String hashedPayload = BinaryUtils.toHex(hash(payload));
        return httpMethod + '\n' + canonicalURIParameter + '\n' + canonicalQueryString + '\n' + canonicalHeaders + '\n' + signedHeader + '\n' + hashedPayload;

    }

    //Step 2: Create a string to sign using sig v4
    public static String createStringToSign(String dateTime, String canonicalRequest, String accessKey, String date, String region) throws Exception {
        String credentialScope = date + "/" + region + "/" + serviceName + "/aws4_request";
        return algorithm + '\n' + dateTime + '\n' + credentialScope + '\n' + BinaryUtils.toHex(hash(canonicalRequest));

    }

    //Step 3: Calculate signature
    /**
     * Step 3 of the &AWS; Signature version 4 calculation. It involves deriving
     * the signing key and computing the signature. Refer to
     * http://docs.aws.amazon
     * .com/general/latest/gr/sigv4-calculate-signature.html
     */
    public static byte[] calculateSignature(String stringToSign,
                                            byte[] signingKey) {
        return sign(stringToSign.getBytes(Charset.forName("UTF-8")), signingKey,
                SigningAlgorithm.HmacSHA256);
    }

    public static byte[] sign(byte[] data, byte[] key,
                          SigningAlgorithm algorithm) throws SdkClientException {
        try {
            Mac mac = algorithm.getMac();
            mac.init(new SecretKeySpec(key, algorithm.toString()));
            return mac.doFinal(data);
        } catch (Exception e) {
            throw new SdkClientException(
                    "Unable to calculate a request signature: "
                            + e.getMessage(), e);
        }
    }

    public static byte[] newSigningKey(String secretKey,
                                   String dateStamp, String regionName, String serviceName) {
        byte[] kSecret = ("AWS4" + secretKey).getBytes(Charset.forName("UTF-8"));
        byte[] kDate = sign(dateStamp, kSecret, SigningAlgorithm.HmacSHA256);
        byte[] kRegion = sign(regionName, kDate, SigningAlgorithm.HmacSHA256);
        byte[] kService = sign(serviceName, kRegion,
                SigningAlgorithm.HmacSHA256);
        return sign(AWS4_TERMINATOR, kService, SigningAlgorithm.HmacSHA256);
    }

    public static byte[] sign(String stringData, byte[] key,
                       SigningAlgorithm algorithm) throws SdkClientException {
        try {
            byte[] data = stringData.getBytes(UTF8);
            return sign(data, key, algorithm);
        } catch (Exception e) {
            throw new SdkClientException(
                    "Unable to calculate a request signature: "
                            + e.getMessage(), e);
        }
    }

    //Step 4: append the signature
    public static String appendSignature(String signature) {
        return requestWithoutSignature + "&X-Amz-Signature=" + signature;
    }

    public static byte[] hash(String s) throws Exception {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(s.getBytes(UTF8));
            return md.digest();
        } catch (Exception e) {
            throw new SdkClientException(
                    "Unable to compute hash while signing request: "
                            + e.getMessage(), e);
        }
    }
}
```

## 連接至資料庫執行個體
<a name="UsingWithRDS.IAMDBAuth.Connecting.Java.AuthToken.Connect"></a>

以下程式碼範例顯示如何產生身分驗證權杖，然後用來連接至執行 MariaDB 或 MySQL 的執行個體。

若要執行此程式碼範例，您需要在 AWS 網站上[適用於 Java 的 AWS SDK](https://aws.amazon.com/sdk-for-java/)找到的 。此外，您還需要下列項目：
+ MySQL Connector/J。本程式碼範本經過 `mysql-connector-java-5.1.33-bin.jar` 的測試。
+ 區域特有的 Amazon RDS 中繼憑證 AWS 。(如需詳細資訊，請參閱「[使用 SSL/TLS 加密與資料庫執行個體或叢集的連線](UsingWithRDS.SSL.md)」。) 在執行時間，類別載入器會在此 Java 程式碼範例所在的同一個目錄中尋找憑證，因此類別載入器可以找到憑證。
+ 視需要修改下列變數的值：
  + `RDS_INSTANCE_HOSTNAME` – 您想要存取之資料庫執行個體的主機名稱。
  + `RDS_INSTANCE_PORT` – 用於連線至 PostgreSQL 資料庫執行個體的連接埠號碼。
  + `REGION_NAME` – 資料庫執行個體執行所在的 AWS 區域。
  + `DB_USER` – 您想要存取的資料庫帳戶。
  + `SSL_CERTIFICATE` – 特定於 AWS 區域的 Amazon RDS SSL 憑證。

    若要下載適用於 AWS 區域的憑證，請參閱[使用 SSL/TLS 加密與資料庫執行個體或叢集的連線](UsingWithRDS.SSL.md)。將 SSL 憑證放入此 Java 程式檔案所在的同一個目錄中，讓類別載入器在執行時間可以找到憑證。

此程式碼範例會從預設 AWS 登入資料提供者鏈結取得登入資料。 [https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html#credentials-default](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html#credentials-default)

**注意**  
為 `DEFAULT_KEY_STORE_PASSWORD` 指定此處所顯示提示以外的密碼，作為安全最佳實務。

```
package com.amazonaws.samples;

import com.amazonaws.services.rds.auth.RdsIamAuthTokenGenerator;
import com.amazonaws.services.rds.auth.GetIamAuthTokenRequest;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.auth.AWSStaticCredentialsProvider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

import java.net.URL;

public class IAMDatabaseAuthenticationTester {
    //&AWS; Credentials of the IAM user with policy enabling IAM Database Authenticated access to the db by the db user.
    private static final DefaultAWSCredentialsProviderChain creds = new DefaultAWSCredentialsProviderChain();
    private static final String AWS_ACCESS_KEY = creds.getCredentials().getAWSAccessKeyId();
    private static final String AWS_SECRET_KEY = creds.getCredentials().getAWSSecretKey();

    //Configuration parameters for the generation of the IAM Database Authentication token
    private static final String RDS_INSTANCE_HOSTNAME = "rdsmysql.123456789012.us-west-2.rds.amazonaws.com";
    private static final int RDS_INSTANCE_PORT = 3306;
    private static final String REGION_NAME = "us-west-2";
    private static final String DB_USER = "jane_doe";
    private static final String JDBC_URL = "jdbc:mysql://" + RDS_INSTANCE_HOSTNAME + ":" + RDS_INSTANCE_PORT;

    private static final String SSL_CERTIFICATE = "rds-ca-2019-us-west-2.pem";

    private static final String KEY_STORE_TYPE = "JKS";
    private static final String KEY_STORE_PROVIDER = "SUN";
    private static final String KEY_STORE_FILE_PREFIX = "sys-connect-via-ssl-test-cacerts";
    private static final String KEY_STORE_FILE_SUFFIX = ".jks";
    private static final String DEFAULT_KEY_STORE_PASSWORD = "changeit";

    public static void main(String[] args) throws Exception {
        //get the connection
        Connection connection = getDBConnectionUsingIam();

        //verify the connection is successful
        Statement stmt= connection.createStatement();
        ResultSet rs=stmt.executeQuery("SELECT 'Success!' FROM DUAL;");
        while (rs.next()) {
        	    String id = rs.getString(1);
            System.out.println(id); //Should print "Success!"
        }

        //close the connection
        stmt.close();
        connection.close();
        
        clearSslProperties();
        
    }

    /**
     * This method returns a connection to the db instance authenticated using IAM Database Authentication
     * @return
     * @throws Exception
     */
    private static Connection getDBConnectionUsingIam() throws Exception {
        setSslProperties();
        return DriverManager.getConnection(JDBC_URL, setMySqlConnectionProperties());
    }

    /**
     * This method sets the mysql connection properties which includes the IAM Database Authentication token
     * as the password. It also specifies that SSL verification is required.
     * @return
     */
    private static Properties setMySqlConnectionProperties() {
        Properties mysqlConnectionProperties = new Properties();
        mysqlConnectionProperties.setProperty("verifyServerCertificate","true");
        mysqlConnectionProperties.setProperty("useSSL", "true");
        mysqlConnectionProperties.setProperty("user",DB_USER);
        mysqlConnectionProperties.setProperty("password",generateAuthToken());
        return mysqlConnectionProperties;
    }

    /**
     * This method generates the IAM Auth Token.
     * An example IAM Auth Token would look like follows:
     * btusi123---cmz7kenwo2ye---rds---cn-north-1.amazonaws.com.rproxy.goskope.com.cn:3306/?Action=connect&DBUser=iamtestuser&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20171003T010726Z&X-Amz-SignedHeaders=host&X-Amz-Expires=899&X-Amz-Credential=AKIAPFXHGVDI5RNFO4AQ%2F20171003%2Fcn-north-1%2Frds-db%2Faws4_request&X-Amz-Signature=f9f45ef96c1f770cdad11a53e33ffa4c3730bc03fdee820cfdf1322eed15483b
     * @return
     */
    private static String generateAuthToken() {
        BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY);

        RdsIamAuthTokenGenerator generator = RdsIamAuthTokenGenerator.builder()
                .credentials(new AWSStaticCredentialsProvider(awsCredentials)).region(REGION_NAME).build();
        return generator.getAuthToken(GetIamAuthTokenRequest.builder()
                .hostname(RDS_INSTANCE_HOSTNAME).port(RDS_INSTANCE_PORT).userName(DB_USER).build());
    }

    /**
     * This method sets the SSL properties which specify the key store file, its type and password:
     * @throws Exception
     */
    private static void setSslProperties() throws Exception {
        System.setProperty("javax.net.ssl.trustStore", createKeyStoreFile());
        System.setProperty("javax.net.ssl.trustStoreType", KEY_STORE_TYPE);
        System.setProperty("javax.net.ssl.trustStorePassword", DEFAULT_KEY_STORE_PASSWORD);
    }

    /**
     * This method returns the path of the Key Store File needed for the SSL verification during the IAM Database Authentication to
     * the db instance.
     * @return
     * @throws Exception
     */
    private static String createKeyStoreFile() throws Exception {
        return createKeyStoreFile(createCertificate()).getPath();
    }

    /**
     *  This method generates the SSL certificate
     * @return
     * @throws Exception
     */
    private static X509Certificate createCertificate() throws Exception {
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        URL url = new File(SSL_CERTIFICATE).toURI().toURL();
        if (url == null) {
            throw new Exception();
        }
        try (InputStream certInputStream = url.openStream()) {
            return (X509Certificate) certFactory.generateCertificate(certInputStream);
        }
    }

    /**
     * This method creates the Key Store File
     * @param rootX509Certificate - the SSL certificate to be stored in the KeyStore
     * @return
     * @throws Exception
     */
    private static File createKeyStoreFile(X509Certificate rootX509Certificate) throws Exception {
        File keyStoreFile = File.createTempFile(KEY_STORE_FILE_PREFIX, KEY_STORE_FILE_SUFFIX);
        try (FileOutputStream fos = new FileOutputStream(keyStoreFile.getPath())) {
            KeyStore ks = KeyStore.getInstance(KEY_STORE_TYPE, KEY_STORE_PROVIDER);
            ks.load(null);
            ks.setCertificateEntry("rootCaCertificate", rootX509Certificate);
            ks.store(fos, DEFAULT_KEY_STORE_PASSWORD.toCharArray());
        }
        return keyStoreFile;
    }
    
    /**
     * This method clears the SSL properties.
     * @throws Exception
     */
    private static void clearSslProperties() throws Exception {
           System.clearProperty("javax.net.ssl.trustStore");
           System.clearProperty("javax.net.ssl.trustStoreType");
           System.clearProperty("javax.net.ssl.trustStorePassword"); 
    }
    
}
```

如果要透過 Proxy 連線到資料庫執行個體，請參閱 [使用 IAM 身分驗證連線至資料庫](rds-proxy-connecting.md#rds-proxy-connecting-iam)。

# 使用 IAM 身分驗證和 連線至資料庫執行個體 適用於 Python (Boto3) 的 AWS SDK
<a name="UsingWithRDS.IAMDBAuth.Connecting.Python"></a>

您可以使用 連線到 RDS for MariaDB、MySQL 或 PostgreSQL 資料庫執行個體 適用於 Python (Boto3) 的 AWS SDK ，如下所述。

**先決條件**  
以下是使用 IAM 身分驗證連線至資料庫執行個體的先決條件：
+ [啟用和停用 IAM 資料庫身分驗證](UsingWithRDS.IAMDBAuth.Enabling.md)
+ [建立並使用 IAM 政策進行 IAM 資料庫存取](UsingWithRDS.IAMDBAuth.IAMPolicy.md)
+ [使用 IAM 身分驗證建立資料庫帳戶](UsingWithRDS.IAMDBAuth.DBAccounts.md)

此外，請確定範例程式碼中匯入的程式庫存在於您的系統上。

**範例**  
程式碼範例使用設定檔進行共用登入資料。如需指定登入資料的資訊，請參閱 適用於 Python (Boto3) 的 AWS SDK 文件中的[登入](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html)資料。

以下程式碼範例顯示如何產生身分驗證字符，然後用來連線至資料庫執行個體。

若要執行此程式碼範例，您需要在 AWS 網站上[適用於 Python (Boto3) 的 AWS SDK](https://aws.amazon.com/sdk-for-python/)找到的 。

視需要修改下列變數的值：
+ `ENDPOINT` – 您想要存取之資料庫執行個體的端點
+ `PORT` – 用於連線資料庫執行個體的連接埠號碼
+ `USER` – 您想要存取的資料庫帳戶
+ `REGION` – 資料庫執行個體執行所在的 AWS 區域
+ `DBNAME` – 您想要存取的資料庫
+ `SSLCERTIFICATE` – Amazon RDS 之 SSL 憑證的完整路徑

  對於 `ssl_ca`，指定 SSL 憑證。若要下載 SSL 憑證，請參閱[使用 SSL/TLS 加密與資料庫執行個體或叢集的連線](UsingWithRDS.SSL.md)。

**注意**  
您無法使用自訂 Route 53 DNS 記錄，替代資料庫執行個體端點來產生身分驗證字符。

此程式碼連接到 MariaDB 或 MySQL 資料庫執行個體。

在執行此程式碼之前，請遵循 [Python 套件索引](https://pypi.org/project/PyMySQL/)中的指示，來安裝 PyMySQL 驅動程式。

```
import pymysql
import sys
import boto3
import os

ENDPOINT="mysqldb.123456789012.us-east-1.rds.amazonaws.com"
PORT="3306"
USER="jane_doe"
REGION="us-east-1"
DBNAME="mydb"
os.environ['LIBMYSQL_ENABLE_CLEARTEXT_PLUGIN'] = '1'

#gets the credentials from .aws/credentials
session = boto3.Session(profile_name='default')
client = session.client('rds')

token = client.generate_db_auth_token(DBHostname=ENDPOINT, Port=PORT, DBUsername=USER, Region=REGION)

try:
    conn =  pymysql.connect(auth_plugin_map={'mysql_clear_password':None},host=ENDPOINT, user=USER, password=token, port=PORT, database=DBNAME, ssl_ca='SSLCERTIFICATE', ssl_verify_identity=True, ssl_verify_cert=True)
    cur = conn.cursor()
    cur.execute("""SELECT now()""")
    query_results = cur.fetchall()
    print(query_results)
except Exception as e:
    print("Database connection failed due to {}".format(e))
```

此程式碼會連線至 PostgreSQL 資料庫執行個體。

在執行此程式碼之前，請按照 [Psycopg 文件](https://pypi.org/project/psycopg2/)中的指示來安裝 `psycopg2`。

```
import psycopg2
import sys
import boto3
import os

ENDPOINT="postgresmydb.123456789012.us-east-1.rds.amazonaws.com"
PORT="5432"
USER="jane_doe"
REGION="us-east-1"
DBNAME="mydb"

#gets the credentials from .aws/credentials
session = boto3.Session(profile_name='RDSCreds')
client = session.client('rds')

token = client.generate_db_auth_token(DBHostname=ENDPOINT, Port=PORT, DBUsername=USER, Region=REGION)

try:
    conn = psycopg2.connect(host=ENDPOINT, port=PORT, database=DBNAME, user=USER, password=token, sslrootcert="SSLCERTIFICATE")
    cur = conn.cursor()
    cur.execute("""SELECT now()""")
    query_results = cur.fetchall()
    print(query_results)
except Exception as e:
    print("Database connection failed due to {}".format(e))
```

如果要透過 Proxy 連線到資料庫執行個體，請參閱 [使用 IAM 身分驗證連線至資料庫](rds-proxy-connecting.md#rds-proxy-connecting-iam)。

# IAM 資料庫身分驗證的疑難排解
<a name="UsingWithRDS.IAMDBAuth.Troubleshooting"></a>

您可在下列內容中找到某些常見 IAM 資料庫身分驗證問題的疑難排解想法，以及 IAM 資料庫身分驗證的 CloudWatch 日誌和指標的相關資訊。

## 將 IAM 資料庫身分驗證錯誤日誌匯出至 CloudWatch Logs
<a name="UsingWithRDS.IAMDBAuth.Troubleshooting.ErrorLogs"></a>

IAM 資料庫身分驗證錯誤日誌會存放在資料庫主機上，您可以將這些日誌匯出至您的 CloudWatch Logs 帳戶。使用此頁面中的日誌和修補方法對 IAM 資料庫身分驗證問題進行疑難排解。

您可以從主控台 AWS CLI、和 RDS API 啟用日誌匯出至 CloudWatch Logs 的功能。如需主控台指示，請參閱 [將資料庫日誌發佈至 Amazon CloudWatch Logs](USER_LogAccess.Procedural.UploadtoCloudWatch.md)。

若要在從 AWS CLI 建立資料庫執行個體時，將您的 IAM 資料庫身分驗證錯誤日誌匯出至 CloudWatch Logs，請使用下列命令：

```
aws rds create-db-instance --db-instance-identifier mydbinstance \
--region us-east-1 \
--db-instance-class db.t3.large \
--allocated-storage 50 \
--engine postgres \
--engine-version 16 \
--port 5432 \
--master-username master \
--master-user-password password \
--publicly-accessible \
--enable-iam-database-authentication \
--enable-cloudwatch-logs-exports=iam-db-auth-error
```

若要在從 AWS CLI 修改資料庫執行個體時，將您的 IAM 資料庫身分驗證錯誤日誌匯出至 CloudWatch Logs，請使用下列命令：

```
aws rds modify-db-instance --db-instance-identifier mydbinstance \
--region us-east-1 \
--cloudwatch-logs-export-configuration '{"EnableLogTypes":["iam-db-auth-error"]}'
```

若要驗證資料庫執行個體是否正在將 IAM 資料庫身分驗證日誌匯出至 CloudWatch Logs，請檢查 `EnabledCloudwatchLogsExports` 參數是否在 `describe-db-instances` 命令的輸出中設定為 `iam-db-auth-error`。

```
aws rds describe-db-instances --region us-east-1 --db-instance-identifier mydbinstance
            ...
            
             "EnabledCloudwatchLogsExports": [
                "iam-db-auth-error"
            ],
            ...
```

## IAM 資料庫身分驗證 CloudWatch 指標
<a name="UsingWithRDS.IAMDBAuth.Troubleshooting.CWMetrics"></a>

Amazon RDS 為您的 Amazon CloudWatch 帳戶提供近乎即時的 IAM 資料庫身分驗證指標。下表列出可使用 CloudWatch 的 IAM 資料庫身分驗證指標：


| 指標 | 描述 | 
| --- | --- | 
|  `IamDbAuthConnectionRequests`  |  使用 IAM 資料庫身分驗證提出的連線要求總數。  | 
|  `IamDbAuthConnectionSuccess`  |  IAM 資料庫身分驗證要求成功總數。  | 
|  `IamDbAuthConnectionFailure`  |  失敗的 IAM 資料庫身分驗證請求總數。  | 
|  `IamDbAuthConnectionFailureInvalidToken`  | 由於字符無效而失敗的 IAM 資料庫身分驗證請求總數。 | 
|  `IamDbAuthConnectionFailureInsufficientPermissions`  |  由於政策或許可不正確而失敗的 IAM 資料庫身分驗證要求總數。  | 
|  `IamDbAuthConnectionFailureThrottling`  |  由於 IAM 資料庫身分驗證限流而失敗的 IAM 資料庫身分驗證要求總數。  | 
|  `IamDbAuthConnectionFailureServerError`  |  由於 IAM 資料庫身分驗證功能中的內部伺服器錯誤而失敗的 IAM 資料庫身分驗證要求總數。  | 

## 常見問題與解決方案
<a name="UsingWithRDS.IAMDBAuth.Troubleshooting.IssuesSolutions"></a>

 使用 IAM 資料庫身分驗證時可能會遇到下列問題。使用資料表中的修補步驟來解決問題：


| 錯誤 | 指標 | 原因 | 解決方案 | 
| --- | --- | --- | --- | 
|  `[ERROR] Failed to authenticate the connection request for user db_user because the provided token is malformed or otherwise invalid. (Status Code: 400, Error Code: InvalidToken)`  |  `IamDbAuthConnectionFailure` `IamDbAuthConnectionFailureInvalidToken`  |  連線要求中的 IAM 資料庫驗證字符不是有效的 SigV4a 字符，或者格式不正確。  |  檢查應用程式中的字符產生策略。在某些情況下，請確定您使用有效的格式傳遞字符。截斷字符 (或不正確的字串格式) 會使字符無效。  | 
|  `[ERROR] Failed to authenticate the connection request for user db_user because the token age is longer than 15 minutes. (Status Code: 400, Error Code:ExpiredToken)`  |  `IamDbAuthConnectionFailure` `IamDbAuthConnectionFailureInvalidToken`  |  IAM 資料庫身分驗證字符已過期。字符的有效時間為 15 分鐘。  |  檢查您應用程式中的字符快取和/或字符重複使用邏輯。您不應重複使用超過 15 分鐘的字符。  | 
|  `[ERROR] Failed to authorize the connection request for user db_user because the IAM policy assumed by the caller 'arn:aws:sts::123456789012:assumed-role/ <RoleName>/ <RoleSession>' is not authorized to perform `rds-db:connect` on the DB instance. (Status Code: 403, Error Code:NotAuthorized)`  |  `IamDbAuthConnectionFailure` `IamDbAuthConnectionFailureInsufficientPermissions`  |  此錯誤可能由下列原因造成： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.Troubleshooting.html)  |  驗證您在應用程式中擔任的 IAM 角色和/或政策。請確定您擔任以產生字符的政策，與連線至資料庫的政策相同。  | 
|  `[ERROR] Failed to authorize the connection request for user db_user due to IAM DB authentication throttling. (Status Code: 429, Error Code: ThrottlingException)`  |  `IamDbAuthConnectionFailure` `IamDbAuthConnectionFailureThrottling`  | 您在短時間內對資料庫提出太多連線要求。IAM 資料庫身分驗證限流限制為每秒 200 個連線。 |  降低使用 IAM 身分驗證建立新連線的速率。請考慮使用 RDS Proxy 實作連線集區，以便在應用程式中重複使用已建立的連線。  | 
|  `[ERROR] Failed to authorize the connection request for user db_user due to an internal IAM DB authentication error. (Status Code: 500, Error Code: InternalError)`  |  `IamDbAuthConnectionFailure` `IamDbAuthConnectionFailureThrottling` |  使用 IAM 資料庫身分驗證授權資料庫連線時發生內部錯誤。  |  請聯絡 https://aws.amazon.com/premiumsupport/ 以調查問題。  | 