

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

# 產生 Amazon Bedrock API 金鑰
<a name="api-keys-generate"></a>

您可以使用 AWS 管理主控台 或 API 產生 Amazon Bedrock AWS API 金鑰。我們建議您使用 AWS 管理主控台 ，只需幾個步驟即可輕鬆產生 Amazon Bedrock API 金鑰。

**警告**  
我們強烈建議限縮將 Amazon Bedrock API 金鑰用於探索 Amazon Bedrock 的用途。當您準備好將 Amazon Bedrock 納入具有更高安全需求的應用程式時，應該切換到短期憑證。如需詳細資訊，請參閱《IAM 使用者指南》中的[長期存取金鑰的替代方案](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys)。

**Topics**
+ [使用主控台產生 Amazon Bedrock API 金鑰](#api-keys-generate-console)
+ [使用 API 產生長期 Amazon Bedrock API 金鑰](#api-keys-generate-api-long-term)
+ [使用用戶端程式庫產生短期 Amazon Bedrock API 金鑰](#api-keys-generate-short-term)
+ [設定自動重新整理短期 Amazon Bedrock API 金鑰](#api-keys-refresh-short-term)

## 使用主控台產生 Amazon Bedrock API 金鑰
<a name="api-keys-generate-console"></a>

若要使用主控台產生 Amazon Bedrock API 金鑰，請執行下列動作：

1.  AWS 管理主控台 使用具有使用 Amazon Bedrock 主控台之許可的 IAM 身分登入 。接著，開啟位於 [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock) 的 Amazon Bedrock 主控台。

1. 在左側導覽窗格中，選取**API 金鑰**。

1. 產生下列其中一種類型的金鑰：
   + **短期 API 金鑰** – 在**短期 API 金鑰**索引標籤中，選擇**產生短期 API 金鑰**。金鑰會在主控台工作階段過期 （且不超過 12 小時） 時過期，並可讓您呼叫您從 AWS 區域 中產生的 。您可以直接在產生的金鑰中修改區域。
   + **長期 API 金鑰** – 在**長期 API 金鑰**索引標籤中，選擇**產生長期 API 金鑰**。

     1. 在 **API 金鑰過期**區段中，選擇金鑰過期的時間。

     1. （選用） 根據預設，授予核心 Amazon Bedrock API 操作存取權的 [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) AWS受管政策會連接至與金鑰相關聯的 IAM 使用者。若要選取更多政策以連接到使用者，請展開**進階許可**區段，然後選取您要新增的政策。

     1. 選擇 **Generate (產生)**。
**警告**  
我們強烈建議限縮將 Amazon Bedrock API 金鑰用於探索 Amazon Bedrock 的用途。當您準備好將 Amazon Bedrock 納入具有更高安全需求的應用程式時，應該切換到短期憑證。如需詳細資訊，請參閱《IAM 使用者指南》中的[長期存取金鑰的替代方案](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys)。



## 使用 API 產生長期 Amazon Bedrock API 金鑰
<a name="api-keys-generate-api-long-term"></a>

在 API 中建立長期 Amazon Bedrock API 金鑰的一般步驟如下：

1. 使用 [IAM 端點](https://docs.aws.amazon.com/general/latest/gr/iam-service.html)傳送 [CreateUser](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html) 請求，來建立 IAM 使用者。

1. 透過使用 [IAM 端點](https://docs.aws.amazon.com/general/latest/gr/iam-service.html)傳送 [AttachUserPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachUserPolicy.html) 請求，將 [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) 連接至 IAM 使用者。您可以重複此步驟，視需要將其他受管或自訂政策連接至使用者。
**注意**  
作為最佳實務，強烈建議您將 IAM 政策連接至 IAM 使用者，以限縮 Amazon Bedrock API 金鑰的使用。如需時間限制政策和限制可使用金鑰之 IP 位址的範例，請參閱[透過將內嵌政策連接至 IAM 使用者來控制存取金鑰的使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-keys_inline-policy.html)。

1. 使用 [IAM 端點](https://docs.aws.amazon.com/general/latest/gr/iam-service.html)傳送 [CreateServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceSpecificCredential.html.html) 請求，並將 `bedrock.amazonaws.com` 指定為 `ServiceName`，以產生長期 Amazon Bedrock API 金鑰。
   + 回應中傳回的 `ServiceApiKeyValue` 是您的長期 Amazon Bedrock API 金鑰。
   + 回應中傳回的 `ServiceSpecificCredentialId` 可用來執行與金鑰相關的 API 操作。

若要了解如何產生長期 Amazon Bedrock API 金鑰，請選擇您偏好方法的索引標籤，然後遵循下列步驟：

------
#### [ CLI ]

若要建立長期 Amazon Bedrock API 金鑰，您可以使用 AWS Identity and Access Management API 操作。首先，請確定您已滿足先決條件：

**先決條件**  
請確定您的設定允許 AWS CLI 自動辨識您的 AWS 登入資料。若要進一步了解，請參閱[設定 AWS CLI的設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)。

開啟終端機並執行下列命令：

1. 建立 IAM 使用者。您可以將名稱取代為您選擇的其中一個名稱：

   ```
   aws iam create-user --user-name bedrock-api-user
   ```

1. 將 [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) 連接至使用者。您可以使用要新增至 API 金鑰的任何其他 AWS受管或自訂政策ARNs 重複此步驟：

   ```
   aws iam attach-user-policy --user-name bedrock-api-user --policy-arn arn:aws:iam::aws:policy/AmazonBedrockLimitedAccess
   ```

1. 建立長期 Amazon Bedrock API 金鑰，以您希望金鑰持續的天數取代 {{${NUMBER-OF-DAYS}}}：

   ```
   aws iam create-service-specific-credential \
       --user-name bedrock-api-user \
       --service-name bedrock.amazonaws.com \
       --credential-age-days {{${NUMBER-OF-DAYS}}}
   ```

------
#### [ Python ]

若要建立長期 Amazon Bedrock API 金鑰，您可以使用 AWS Identity and Access Management API 操作。首先，請確定您已滿足先決條件：

**先決條件**  
請確定您的設定允許 Python 自動辨識您的 AWS 登入資料。若要進一步了解，請參閱[設定 AWS CLI的設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)。

執行下列指令碼來建立 IAM 使用者、連接執行 Amazon Bedrock 動作的許可，以及產生要與使用者建立關聯的長期 Amazon Bedrock API 金鑰：

```
import boto3
from datetime import datetime, timedelta

# Replace with name for your IAM user
username = "bedrock-api-user"
# Add any AWS-managed or custom policies that you want to the user
bedrock_policies = [
    "arn:aws:iam::aws:policy/AmazonBedrockLimitedAccess",        # Limited access
#    "arn:aws:iam::aws:policy/AmazonBedrockMarketplaceAccess",   # Optional: Access to Amazon Bedrock Marketplace actions
]
# Set the key expiration time to a number of your choice
expiration_time_in_days = 30

iam_client = boto3.client("iam")
    
# Create IAM user
user = iam_client.create_iam_user(username)

# Attach policies to user
for policy_arn in bedrock_policies:
    iam_client.attach_managed_policy(username, policy_arn)

# Create long-term Amazon Bedrock API key and return it
service_credentials = iam_client.create_service_specific_credential(
    user_name=username, 
    service_name="bedrock",
    credential_age_days=expiration_time_in_days
) 
api_key = service_credentials["ServiceApiKeyValue"]
print(api_key)
```

------

## 使用用戶端程式庫產生短期 Amazon Bedrock API 金鑰
<a name="api-keys-generate-short-term"></a>

短期金鑰具有下列屬性：
+ 有效期限為下列值中較短者：
  + 12 小時
  + 由 IAM 主體產生，用於產生金鑰的工作階段持續時間。
+ 繼承用於產生金鑰之主體所連接的許可。
+ 只能在您產生它的 AWS 區域中使用。

對於長時間執行的應用程式，[aws-bedrock-token-generator](https://github.com/aws/aws-bedrock-token-generator-js/blob/main/README.md) 用戶端程式庫可以在重新整理憑證時，視需要建立新的 Amazon Bedrock 短期 API 金鑰。如需詳細資訊，請參閱[設定自動重新整理短期 Amazon Bedrock API 金鑰](#api-keys-refresh-short-term)。

**先決條件**
+ 確保您用來產生金鑰的 IAM 主體已設定適當的許可，可以使用 Amazon Bedrock。針對實驗，您可以將 AWS受管 [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) 政策連接至委託人。您可以參考 [IAM 中的安全最佳實務](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)來保護您的憑證。
+ 請確定您的設定允許 Python 自動辨識您的 AWS 登入資料。擷取憑證的預設方法遵循既定的階層。您可以在 [AWS SDK 和工具標準化憑證提供者](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html)中查看特定 SDK 或工具的階層。
+ 安裝 Amazon Bedrock 字符產生器。選擇您偏好方法的索引標籤，然後遵循下列步驟：

------
#### [ Python ]

開啟終端機並執行下列命令：

```
pip install aws-bedrock-token-generator
```

------
#### [ Javascript ]

開啟終端機並執行下列命令：

```
npm install @aws/bedrock-token-generator
```

------
#### [ Java ]

如果您使用 Maven，請將以下相依性新增到您的 `pom.xml`：

```
<dependency>
    <groupId>software.amazon.bedrock</groupId>
    <artifactId>aws-bedrock-token-generator</artifactId>
    <version>1.1.0</version>
</dependency>
```

如果您使用 Gradle，請將下列項目新增至您的 `build.gradle`：

```
implementation 'software.amazon.bedrock:aws-bedrock-token-generator:1.1.0'
```

------

**範例**  
若要查看如何使用字符產生器以不同語言產生包含預設憑證的短期 Amazon Bedrock API 金鑰的範例，請選擇您偏好方法的索引標籤，然後遵循下列步驟：

------
#### [ Python ]

```
from aws_bedrock_token_generator import provide_token

token = provide_token()
print(f"Token: {token}")
```

------
#### [ Javascript ]

```
import { getTokenProvider } from "@aws/bedrock-token-generator";

// Create a token provider that uses default credentials and region providers.
// You can configure it to use other credential providers.
const provideToken = getTokenProvider();

async function example() {
    
  const token = await provideToken();

  // Use the token for API calls. The token has a default expiration of 12 hour.
  // If the expiresInSeconds parameter is specified during token creation, the 
  // expiration can be configured up to a maximum of 12 hours. However, the actual 
  // token validity period will always be the minimum of the requested expiration 
  // time and the AWS credentials' expiry time
  console.log(`Bearer Token: ${token}`);
}
```

------
#### [ Java ]

```
import software.amazon.bedrock.token.BedrockTokenGenerator;

// Credentials and region will be picked up from the default provider chain
BedrockTokenGenerator tokenGenerator = BedrockTokenGenerator.builder().build();
tokenGenerator.getToken();
```

------

若要查看產生字符時不同使用案例的更多範例，請參閱以下連結：
+ [Python](https://github.com/aws/aws-bedrock-token-generator-python/blob/main/README.md)
+ [Javascript](https://github.com/aws/aws-bedrock-token-generator-js/blob/main/README.md)
+ [Java](https://github.com/aws/aws-bedrock-token-generator-java/blob/main/README.md)

## 設定自動重新整理短期 Amazon Bedrock API 金鑰
<a name="api-keys-refresh-short-term"></a>

您可以在 `aws-bedrock-token-generator` 套件的協助下建立指令碼，以程式設計方式在目前金鑰過期時重新產生新的短期金鑰。首先，請確定您已滿足[使用用戶端程式庫產生短期 Amazon Bedrock API 金鑰](#api-keys-generate-short-term)的先決條件。若要查看擷取字符並提出 Converse 請求的範例指令碼，請選擇您偏好方法的標籤，然後遵循以下步驟：

------
#### [ Python ]

```
from aws_bedrock_token_generator import provide_token
import requests

def get_new_token():
    url = "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/converse"
    payload = {
        "messages": [
            {
                "role": "user",
                "content": [{"text": "Hello"}]
            }
        ]
    }

    # Create a token provider that uses default credentials and region providers.
    # You can configure it to use other credential providers.
    # https://github.com/aws/aws-bedrock-token-generator-python/blob/main/README.md
    # It can be used for each API call as it is inexpensive.
    token = provide_token()

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}"
    }

    response = requests.post(url, headers=headers, json=payload)
    print(response.json())

if __name__ == "__main__":
    get_new_token()
```

------
#### [ Javascript ]

```
import { getTokenProvider } from "@aws/bedrock-token-generator";

// Create a token provider that uses default credentials and region providers.
// You can configure it to use other credential providers.
// https://github.com/aws/aws-bedrock-token-generator-js/blob/main/README.md
// This can be created just once. Use await provideToken() to fetch the token
const provideToken = getTokenProvider();

async function example() {
    const url = "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/converse";
    const payload = {
        messages: [
            {
                role: "user",
                content: [{ text: "Hello" }]
            }
        ]
    };
    const headers = {
        "Content-Type": "application/json",
        // provideToken retrieves a valid token. It can be used for each API call as it is inexpensive.
        "Authorization": `Bearer ${await provideToken()}`
    };
    await fetch(url, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(payload)
    })
}
```

------
#### [ Java ]

```
package com.amazon.bedrocktoken;

import software.amazon.bedrock.token.BedrockTokenGenerator;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class GetNewToken {
    public static void main(String[] args) throws Exception {
        // Use default credentials and region from environment/profile chain
        // Create a token generator that uses default credentials and region providers.
        // You can configure it to use other credential providers.
        // https://github.com/aws/aws-bedrock-token-generator-java/blob/main/README.md
        BedrockTokenGenerator tokenGenerator = BedrockTokenGenerator.builder().build();

        // getToken() retrieves a valid token. It can be used for each API call as it is inexpensive.
        String token = tokenGenerator.getToken();

        String url = "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.anthropic.claude-sonnet-4-6/converse";
        String payload = "{\n" +
                "    \"messages\": [\n" +
                "        {\n" +
                "            \"role\": \"user\",\n" +
                "            \"content\": [{ \"text\": \"Hello\" }]\n" +
                "        }\n" +
                "    ]\n" +
                "}";

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Content-Type", "application/json")
            .header("Authorization", "Bearer " + token)
            .POST(HttpRequest.BodyPublishers.ofString(payload))
            .build();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
```

------