

# API keys
<a name="api-keys"></a>

You can easily make calls to the Amazon Bedrock API by generating an Amazon Bedrock API key and using it to authenticate your identity when making requests to the Amazon Bedrock API.

**Note**  
For audit and compliance purposes, all API calls are logged in AWS CloudTrail. Amazon Bedrock API keys are passed as authorization headers to API requests and aren’t logged.  
Amazon Bedrock API keys are limited to [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock.html) and [Amazon Bedrock Runtime](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock_Runtime.html) actions. You can't use them with the following API operations:  
[InvokeModelWithBidirectionalStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithBidirectionalStream.html).
[Agents for Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Agents_for_Amazon_Bedrock.html) or [Agents for Amazon Bedrock Runtime](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Agents_for_Amazon_Bedrock.html) API operations.
[Data Automation for Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Data_Automation_for_Amazon_Bedrock.html) or [Runtime for Amazon Bedrock Data Automation](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Runtime_for_Amazon_Bedrock_Data_Automation) API operations.

Amazon Bedrock allows you to generate the following kinds of Amazon Bedrock API keys:
+ **Short-term** – Create an Amazon Bedrock API key that lasts as long as your session (and no longer than 12 hours). You should already have an [IAM principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_identity-management.html#intro-structure-terms) set up with the proper permissions to use Amazon Bedrock. This option is preferred over long-term keys for production environments that require regular changing of credentials for greater security.

  Short term keys have the following properties:
  + Valid for the shorter of the following values:
    + 12 hours
    + The duration of the session generated by the IAM principal used to generate the key.
  + Inherit the permissions attached to the principal used to generate the key.
  + Can be used only in the AWS Region from which you generated it.
+ **Long-term** – Create an Amazon Bedrock API key with permissions to make basic API requests in Amazon Bedrock. This easy one-click option lets you quickly begin exploring the Amazon Bedrock API without needing to understand the underlying security infrastructure or manually configuring AWS Identity and Access Management permissions. If you're trying out Amazon Bedrock for the first time, you can try out the example at [Get started with Amazon Bedrock API keys: Generate a 30-day key and make your first API call](getting-started-api-keys.md) for an easy tutorial to create a long-term key and get started using Amazon Bedrock.
**Warning**  
We strongly recommend restricting the use of Amazon Bedrock API keys for exploration of Amazon Bedrock. When you're ready to incorporate Amazon Bedrock into applications with greater security requirements, you should switch to short-term credentials. For more information, see [Alternatives to long-term access keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys) in the IAM User Guide.

Select a topic to learn more about Amazon Bedrock API keys. There are various options for different types of Amazon Bedrock keys and ways to customize them. For a quickstart tutorial for how to generate a long-term Amazon Bedrock API key and use it for exploratory purposes, see [Get started with Amazon Bedrock API keys: Generate a 30-day key and make your first API call](getting-started-api-keys.md).

**Topics**
+ [

# How Amazon Bedrock API keys work
](api-keys-how.md)
+ [

# Supported Regions and AWS software development kits (SDKs) for Amazon Bedrock API keys
](api-keys-supported.md)
+ [

# Generate an Amazon Bedrock API key
](api-keys-generate.md)
+ [

# Use an Amazon Bedrock API key
](api-keys-use.md)
+ [

# Modify permissions for long-term and short-term Amazon Bedrock API keys
](api-keys-modify.md)
+ [

# Handle compromised long-term and short-term Amazon Bedrock API keys
](api-keys-revoke.md)
+ [

# Control permissions for generating and using Amazon Bedrock API keys
](api-keys-permissions.md)

# How Amazon Bedrock API keys work
<a name="api-keys-how"></a>

The following image compares the default process to get credentials to the use of the Amazon Bedrock API key:

![\[Default API setup process compared to API setup process using Amazon Bedrock API key\]](http://docs.aws.amazon.com/bedrock/latest/userguide/images/setup/setup-api.png)


The leftmost flow in the diagram shows the default process of creating an identity in either AWS IAM Identity Center or IAM. With this process, you attach IAM policies to that identity to provide permissions to perform API operations and then generate general AWS credentials for that identity. You can then use the credentials to make API calls in AWS.

The blue nodes indicate two more flows to authenticate specifically to Amazon Bedrock. Both flows involve creating an Amazon Bedrock API key with which you can authenticate to using Amazon Bedrock actions. You can generate the following types of keys:
+ **Short-term key** – A secure option that allows temporary access to using Amazon Bedrock.

  Short term keys have the following properties:
  + Valid for the shorter of the following values:
    + 12 hours
    + The duration of the session generated by the IAM principal used to generate the key.
  + Inherit the permissions attached to the principal used to generate the key.
  + Can be used only in the AWS Region from which you generated it.
+ **Long-term key** – Recommended only for exploration of Amazon Bedrock. You can set the time after which the key expires. When you generate a long-term key, it underlyingly creates an IAM user that's for you, attaches the IAM policies that you select, and associates the key with the user. After you generate the key, you can use the IAM service to [modify permissions for the IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html).
**Warning**  
We strongly recommend restricting the use of Amazon Bedrock API keys for exploration of Amazon Bedrock. When you're ready to incorporate Amazon Bedrock into applications with greater security requirements, you should switch to short-term credentials. For more information, see [Alternatives to long-term access keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys) in the IAM User Guide.

# Supported Regions and AWS software development kits (SDKs) for Amazon Bedrock API keys
<a name="api-keys-supported"></a>

The following list shows the AWS Regions that support API keys:
+ ap-northeast-1
+ ap-northeast-2
+ ap-northeast-3
+ ap-south-1
+ ap-south-2
+ ap-southeast-1
+ ap-southeast-2
+ ca-central-1
+ eu-central-1
+ eu-central-2
+ eu-north-1
+ eu-south-1
+ eu-south-2
+ eu-west-1
+ eu-west-2
+ eu-west-3
+ sa-east-1
+ us-east-1
+ us-gov-east-1
+ us-gov-west-1
+ us-west-2

**Note**  
Amazon Bedrock API keys are limited to [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock.html) and [Amazon Bedrock Runtime](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock_Runtime.html) actions. You can't use them with the following API operations:  
[InvokeModelWithBidirectionalStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithBidirectionalStream.html).
[Agents for Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Agents_for_Amazon_Bedrock.html) or [Agents for Amazon Bedrock Runtime](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Agents_for_Amazon_Bedrock.html) API operations.
[Data Automation for Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Data_Automation_for_Amazon_Bedrock.html) or [Runtime for Amazon Bedrock Data Automation](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Runtime_for_Amazon_Bedrock_Data_Automation) API operations.

Amazon Bedrock API keys are supported with the following AWS SDKs:
+ Python
+ Javascript
+ Java

# Generate an Amazon Bedrock API key
<a name="api-keys-generate"></a>

You can generate an Amazon Bedrock API key using either the AWS Management Console or the AWS API. We recommend that you use the AWS Management Console to easily generate an Amazon Bedrock API key with few steps.

**Warning**  
We strongly recommend restricting the use of Amazon Bedrock API keys for exploration of Amazon Bedrock. When you're ready to incorporate Amazon Bedrock into applications with greater security requirements, you should switch to short-term credentials. For more information, see [Alternatives to long-term access keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys) in the IAM User Guide.

**Topics**
+ [

## Generate an Amazon Bedrock API key using the console
](#api-keys-generate-console)
+ [

## Generate a long-term Amazon Bedrock API key using the API
](#api-keys-generate-api-long-term)
+ [

## Generate a short-term Amazon Bedrock API key using a client library
](#api-keys-generate-short-term)
+ [

## Set up automatic refresh of short-term Amazon Bedrock API keys
](#api-keys-refresh-short-term)

## Generate an Amazon Bedrock API key using the console
<a name="api-keys-generate-console"></a>

To generate an Amazon Bedrock API key using the console, do the following:

1. Sign in to the AWS Management Console with an IAM identity that has permissions to use the Amazon Bedrock console. Then, open the Amazon Bedrock console at [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock).

1. In the left navigation pane, select **API keys**.

1. Generate one of the following types of keys:
   + **Short-term API key** – In the **Short-term API keys** tab, choose **Generate short-term API keys**. The key expires when your console session expires (and no longer than 12 hours) and lets you make calls to the AWS Region that you generated it from. You can modify the Region directly in the generated key.
   + **Long-term API key** – In the **Long-term API keys** tab, choose **Generate long-term API keys**.

     1. In the **API key expiration** section, choose a time after which the key will expire.

     1. (Optional) By default, the [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) AWS-managed policy, which grants access to core Amazon Bedrock API operations, is attached to the IAM user associated with the key. To select more policies to attach to the user, expand the **Advanced permissions** section and select the policies that you want to add.

     1. Choose **Generate**.
**Warning**  
We strongly recommend restricting the use of Amazon Bedrock API keys for exploration of Amazon Bedrock. When you're ready to incorporate Amazon Bedrock into applications with greater security requirements, you should switch to short-term credentials. For more information, see [Alternatives to long-term access keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys) in the IAM User Guide.



## Generate a long-term Amazon Bedrock API key using the API
<a name="api-keys-generate-api-long-term"></a>

The general steps for creating a long-term Amazon Bedrock API key in the API are as follows:

1. Create an IAM user by sending a [CreateUser](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html) request with an [IAM endpoint](https://docs.aws.amazon.com/general/latest/gr/iam-service.html).

1. Attach the [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) to the IAM user by sending an [AttachUserPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachUserPolicy.html) request with an [IAM endpoint](https://docs.aws.amazon.com/general/latest/gr/iam-service.html). You can repeat this step to attach other managed or custom policies as necessary to the user.
**Note**  
As a best security practice, we strongly recommend that you attach IAM policies to the IAM user to restrict the use of Amazon Bedrock API keys. For examples of time-bounding policies and restricting the IP addresses that can use the key, see [Control the use of access keys by attaching an inline policy to an IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-keys_inline-policy.html).

1. Generate the long-term Amazon Bedrock API key by sending a [CreateServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceSpecificCredential.html.html) request with an [IAM endpoint](https://docs.aws.amazon.com/general/latest/gr/iam-service.html) and specifying `bedrock.amazonaws.com` as the `ServiceName`.
   + The `ServiceApiKeyValue` returned in the response is your long-term Amazon Bedrock API key.
   + The `ServiceSpecificCredentialId` returned in the response can be used to carry out API operations related to the key.

To learn how to generate a long-term Amazon Bedrock API key, choose the tab for your preferred method, and then follow the steps:

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

To create a long-term Amazon Bedrock API key, you use AWS Identity and Access Management API operations. First, make sure that you've fulfilled the prerequisite:

**Prerequisite**  
Ensure that your setup allows the AWS CLI to automatically recognize your AWS credentials. To learn more, see [Configuring settings for the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html).

Open a terminal and run the following commands:

1. Create an IAM user. You can replace the name with one of your choice:

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

1. Attach the [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) to the user. You can repeat this step with the ARNs of any other AWS-managed or custom policies you want to add to the API key:

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

1. Create the long-term Amazon Bedrock API key, replacing *\$1\$1NUMBER-OF-DAYS\$1* with the number of days for which you want the key to last:

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

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

To create a long-term Amazon Bedrock API key, you use AWS Identity and Access Management API operations. First, make sure that you've fulfilled the prerequisite:

**Prerequisite**  
Ensure that your setup allows Python to automatically recognize your AWS credentials. To learn more, see [Configuring settings for the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html).

Run the following script to create an IAM user, attach permissions to perform Amazon Bedrock actions, and generate a long-term Amazon Bedrock API key to associate with the user:

```
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)
```

------

## Generate a short-term Amazon Bedrock API key using a client library
<a name="api-keys-generate-short-term"></a>

Short term keys have the following properties:
+ Valid for the shorter of the following values:
  + 12 hours
  + The duration of the session generated by the IAM principal used to generate the key.
+ Inherit the permissions attached to the principal used to generate the key.
+ Can be used only in the AWS Region from which you generated it.

For long-running applications, the [aws-bedrock-token-generator](https://github.com/aws/aws-bedrock-token-generator-js/blob/main/README.md) client library can create new Amazon Bedrock short-term API keys as needed when credentials are refreshed. For more information, see [Set up automatic refresh of short-term Amazon Bedrock API keys](#api-keys-refresh-short-term).

**Prerequisites**
+ Ensure that the IAM principal that you use to generate the key is set up with the proper permissions to use Amazon Bedrock. For experimentation, you can attach the AWS-managed [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) policy to the principal. You can refer to the [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) for protecting your credentials.
+ Ensure that your setup allows Python to automatically recognize your AWS credentials. The default method by which credentials are retrieved follows a defined hierarchy. You can see the hierarchy for a specific SDK or tool at [AWS SDKs and Tools standardized credential providers](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html).
+ Install the Amazon Bedrock token generator. Choose the tab for your preferred method, and then follow the steps:

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

Open a terminal and run the following command:

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

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

Open a terminal and run the following command:

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

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

If you use Maven, add the following dependency to your `pom.xml`:

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

If you use Gradle, add the following to your `build.gradle`:

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

------

**Examples**  
To see examples for using the token generator to generate a short-term Amazon Bedrock API key with your default credentials in different languages, choose the tab for your preferred method, and then follow the steps:

------
#### [ 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();
```

------

To see more examples for different use cases when generating tokens, see the following links:
+ [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)

## Set up automatic refresh of short-term Amazon Bedrock API keys
<a name="api-keys-refresh-short-term"></a>

You can create a script with the help of the `aws-bedrock-token-generator` package to programmatically regenerate a new short-term key whenever your current one has expired. First, ensure that you've fulfilled the prerequisites at [Generate a short-term Amazon Bedrock API key using a client library](#api-keys-generate-short-term). To see example scripts that retrieve a token and make a Converse request, choose the tab for your preferred method, and then follow the steps:

------
#### [ 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-3-5-haiku-20241022-v1:0/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-3-5-haiku-20241022-v1:0/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-3-5-haiku-20241022-v1:0/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());
    }
}
```

------

# Use an Amazon Bedrock API key
<a name="api-keys-use"></a>

You can use your Amazon Bedrock API key in the following ways:
+ **Set it as environment variable** – The Amazon Bedrock service recognizes the environment variable `AWS_BEARER_TOKEN_BEDROCK` You have the following options to set the key:
  + Open a terminal to set it:
    + **MacOS/Linux**

      ```
      export AWS_BEARER_TOKEN_BEDROCK=${api-key}
      ```
    + **Windows**

      ```
      setx AWS_BEARER_TOKEN_BEDROCK "${api-key}"
      ```
  + Set it as an environment variable in your code before you make the API request. For example, you could include the following lines before making the request:
    + **Python**

      ```
      import os                      
      os.environ['AWS_BEARER_TOKEN_BEDROCK'] = "${api-key}"
      ```
+ **Specify it in a request** – You can include the Amazon Bedrock API key in the authorization header in the following ways (replace *\$1AWS\$1BEARER\$1TOKEN\$1BEDROCK* with the actual value):
  + **In a direct HTTP request** – Include the following as an authorization header:

    ```
    Authorization: Bearer $AWS_BEARER_TOKEN_BEDROCK
    ```
  + **As a parameter in a supported SDK** – Specify the value in the parameter when setting up the client. For example, you can specify it in the `api_key` field when setting up a client with the [OpenAI Python SDK](https://github.com/openai/openai-python?tab=readme-ov-file#usage).

**Note**  
Amazon Bedrock API keys are limited to [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock.html) and [Amazon Bedrock Runtime](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock_Runtime.html) actions. You can't use them with the following API operations:  
[InvokeModelWithBidirectionalStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithBidirectionalStream.html).
[Agents for Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Agents_for_Amazon_Bedrock.html) or [Agents for Amazon Bedrock Runtime](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Agents_for_Amazon_Bedrock.html) API operations.
[Data Automation for Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Data_Automation_for_Amazon_Bedrock.html) or [Runtime for Amazon Bedrock Data Automation](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Runtime_for_Amazon_Bedrock_Data_Automation) API operations.

To see an example of using the API key to send a [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) request to generate a response, choose the tab for your preferred method, and then follow the steps:

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

The following example shows how to send an API request with the AWS SDK for Python (Boto3). If you didn't already set the API key as the `AWS_BEARER_TOKEN_BEDROCK` environment variable, specify it in place of *\$1\$1api-key\$1* in the following code:

```
import os
import boto3
                        
# If you already set the API key as an environment variable, you can comment this line out                        
os.environ['AWS_BEARER_TOKEN_BEDROCK'] = "${api-key}"

# Create an Amazon Bedrock client
client = boto3.client(
    service_name="bedrock-runtime",
    region_name="us-east-1" # If you've configured a default region, you can omit this line
)

# Define the model and message
model_id = "us.anthropic.claude-3-5-haiku-20241022-v1:0"
messages = [{"role": "user", "content": [{"text": "Hello"}]}]

response = client.converse(
    modelId=model_id,
    messages=messages,
)
```

------
#### [ HTTP Client (requests package in Python) ]

**Prerequisite:** Install the `requests` package by opening a terminal and running the following command:

```
python3 -m pip install requests
```

The following example shows how to directly send an API request with an HTTP client. Specify the *\$1\$1api-key\$1* in the header.

```
import requests

url = "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse"

payload = {
    "messages": [
        {
            "role": "user",
            "content": [{"text": "Hello"}]
        }
    ]
}

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer ${api-key}"
}

response = requests.request("POST", url, json=payload, headers=headers)

print(response.text)
```

------
#### [ HTTP request using cURL ]

The following example shows how to directly send an API request, using cURL. If you didn't set the API key as the AWS\$1BEARER\$1TOKEN\$1BEDROCK environment variable, you'll have to replace `$AWS_BEARER_TOKEN_BEDROCK` in the example with the literal value of the key.

```
curl -X POST "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AWS_BEARER_TOKEN_BEDROCK" \
  -d '{
    "messages": [
        {
            "role": "user",
            "content": [{"text": "Hello"}]
        }
    ]
  }'
```

------

# Modify permissions for long-term and short-term Amazon Bedrock API keys
<a name="api-keys-modify"></a>

When you generate a long-term Amazon Bedrock API key, you create an IAM user associated with the key. To change the permissions associated with the key, modify permissions for the IAM user through the IAM service. For more information, see [Adding and removing IAM identity permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) in the IAM User Guide.

**Note**  
If you generated the long-term key in the AWS Management Console, the [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) is attached to it by default. If you plan to modify permissions, remove this policy first before setting custom permissions.

## Example of modifying permissions for API keys
<a name="api-keys-modify-example"></a>

The following procedure shows how you can replace the [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) with a more restrictive one:

1. Sign in to the AWS Management Console with an IAM identity that has permissions to use the Amazon Bedrock console. Then, open the Amazon Bedrock console at [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock).

1. From the left navigation pane, select **API keys**.

1. Select the **Long-term API keys** tab.

1. Select your API key and choose **Manage in IAM Console**.

1. Select the **Permissions** tab, choose the **AmazonBedrockLimitedAccess** policy, and choose **Remove**.
**Note**  
At this point, you've removed all permissions from the APi key and you won't be able to do anything with it.

1. In the **Permissions policies** section, select **Create inline policy** from the **Add permissions** dropdown.

1. In the **Policy editor**, select **JSON**. Then paste the following policy into the editor:

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "bedrock:CallWithBearerToken"
               ],
               "Resource": "*"
           },
           {
               "Effect": "Allow",
               "Action": [
                   "bedrock:InvokeModel*"
               ],
               "Resource": [
                   "arn:aws:bedrock:us-west-2:111122223333:inference-profile/us.anthropic.claude-3-haiku-20240307-v1:0"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "bedrock:InvokeModel*"
               ],
               "Resource": [
                   "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-haiku-20240307-v1:0",
                   "arn:aws:bedrock:us-west-2::foundation-model/anthropic.claude-3-haiku-20240307-v1:0"
               ],
               "Condition": {
                   "StringLike": {
                       "bedrock:InferenceProfileArn": "arn:aws:bedrock:us-west-2:111122223333:inference-profile/us.anthropic.claude-3-haiku-20240307-v1:0"
                   }
               }
           }
       ]
   }
   ```

------

1. Choose **Next**, provide a **Policy name**, and then choose **Create policy**.

1. With this API key, a user now can only run inference with the US Anthropic Claude 3 Haiku inference profile in US West (Oregon).

# Handle compromised long-term and short-term Amazon Bedrock API keys
<a name="api-keys-revoke"></a>

If your API key becomes compromised, you should revoke permissions to use it. There are various methods that you can use to revoke permissions for an Amazon Bedrock API key:
+ For long-term Amazon Bedrock API keys, you can use the [UpdateServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateServiceSpecificCredential.html.html), [ResetServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResetServiceSpecificCredential.html.html), or [DeleteServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteServiceSpecificCredential.html.html) to revoke permissions in the following ways:
  + Set the status of the key to inactive. You can reactivate the key later.
  + Reset the key. This action generates a new password for the key.
  + Delete the key permanently.
**Note**  
To carry out these actions through the API, you must authenticate with AWS credentials and not with an Amazon Bedrock API key.
+ For both long-term and short-term Amazon Bedrock API keys, you can attach IAM policies to revoke permissions.

**Topics**
+ [

## Change the status of a long-term Amazon Bedrock API key
](#api-keys-change-status)
+ [

## Reset a long-term Amazon Bedrock API key
](#api-keys-reset)
+ [

## Delete a long-term Amazon Bedrock API key
](#api-keys-delete)
+ [

## Attach IAM policies to remove permissions for using an Amazon Bedrock API key
](#api-keys-iam-policies)

## Change the status of a long-term Amazon Bedrock API key
<a name="api-keys-change-status"></a>

If you need to prevent a key from being used temporarily, deactivate it. After you're ready for it to be used again, reactivate it.

Choose the tab for your preferred method, and then follow the steps:

------
#### [ Console ]

**To deactivate a key**

1. Sign in to the AWS Management Console with an IAM identity that has permissions to use the Amazon Bedrock console. Then, open the Amazon Bedrock console at [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock).

1. In the left navigation pane, select **API keys**.

1. In the **Long-term API keys** section, choose a key whose **Status** is **Inactive**.

1. Choose **Actions**.

1. Select **Deactivate**.

1. To confirm, select **Deactivate API key**. The **Status** of the key becomes **Inactive**.

**To reactivate a key**

1. Sign in to the AWS Management Console with an IAM identity that has permissions to use the Amazon Bedrock console. Then, open the Amazon Bedrock console at [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock).

1. In the left navigation pane, select **API keys**.

1. In the **Long-term API keys** section, choose a key whose **Status** is **Inactive**.

1. Choose **Actions**.

1. Select **Activate**.

1. To confirm, select **Activate API key**. The **Status** of the key becomes **Active**.

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

To deactivate a key using the API, send an [UpdateServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateServiceSpecificCredential.html.html) request with an [IAM endpoint](https://docs.aws.amazon.com/general/latest/gr/iam-service.html) and specify the `Status` as `Inactive`. You can use the following code snippet to deactivate a key, replacing *\$1\$1ServiceSpecificCredentialId\$1* with the value returned when you created the key.

```
import boto3
                        
iam_client = boto3.client("iam")
                      
iam_client.update_service_specific_credential(
    service_specific_credential_id=${ServiceSpecificCredentialId},
    status="Inactive"
)
```

To reactivate a key using the API, send an [UpdateServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateServiceSpecificCredential.html.html) request with an [IAM endpoint](https://docs.aws.amazon.com/general/latest/gr/iam-service.html) and specify the `Status` as `Active`. You can use the following code snippet to reactivate a key, replacing *\$1\$1ServiceSpecificCredentialId\$1* with the value returned when you created the key.

```
import boto3
                        
iam_client = boto3.client("iam")
                      
iam_client.update_service_specific_credential(
    service_specific_credential_id=${ServiceSpecificCredentialId},
    status="Active"
)
```

------

## Reset a long-term Amazon Bedrock API key
<a name="api-keys-reset"></a>

If the value of your key has been compromised or you no longer have it, reset it. The key must not have expired yet. If it's already expired, delete the key and create a new one.

Choose the tab for your preferred method, and then follow the steps:

------
#### [ Console ]

**To reset a key**

1. Sign in to the AWS Management Console with an IAM identity that has permissions to use the Amazon Bedrock console. Then, open the Amazon Bedrock console at [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock).

1. In the left navigation pane, select **API keys**.

1. In the **Long-term API keys** section, choose a key.

1. Choose **Actions**.

1. Select **Reset key**.

1. Select **Next**.

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

To reset a key using the API, send a [ResetServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResetServiceSpecificCredential.html.html) request with an [IAM endpoint](https://docs.aws.amazon.com/general/latest/gr/iam-service.html). You can use the following code snippet to reset a key, replacing *\$1\$1ServiceSpecificCredentialId\$1* with the value returned when you created the key.

```
import boto3
            
iam_client = boto3.client("iam")
          
iam_client.reset_service_specific_credential(
    service_specific_credential_id=${ServiceSpecificCredentialId}
)
```

------

## Delete a long-term Amazon Bedrock API key
<a name="api-keys-delete"></a>

If you no longer need a key or it has expired, delete it.

Choose the tab for your preferred method, and then follow the steps:

------
#### [ Console ]

**To delete a key**

1. Sign in to the AWS Management Console with an IAM identity that has permissions to use the Amazon Bedrock console. Then, open the Amazon Bedrock console at [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock).

1. In the left navigation pane, select **API keys**.

1. In the **Long-term API keys** section, choose a key.

1. Choose **Actions**.

1. Select **Delete**.

1. Confirm the deletion.

**An API key is linked with an IAM user**  
Deleting this API key doesn't delete the IAM user which was created with this key as the owner. You can delete the IAM user from IAM console in the next step.

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

To delete a key using the API, send a [DeleteServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteServiceSpecificCredential.html.html) request with an [IAM endpoint](https://docs.aws.amazon.com/general/latest/gr/iam-service.html). You can use the following code snippet to delete a key, replacing *\$1\$1ServiceSpecificCredentialId\$1* with the value returned when you created the key.

```
import boto3
            
iam_client = boto3.client("iam")
          
iam_client.delete_service_specific_credential(
    service_specific_credential_id=${ServiceSpecificCredentialId}
)
```

------

## Attach IAM policies to remove permissions for using an Amazon Bedrock API key
<a name="api-keys-iam-policies"></a>

This section provides some IAM policies that you can use to restrict access to an Amazon Bedrock API key.

### Deny an identity the ability to make calls with an Amazon Bedrock API key
<a name="api-keys-iam-policies-deny-call-with-bearer-token"></a>

The action that allows an identity to make calls with an Amazon Bedrock API key is `bedrock:CallWithBearerToken`. To prevent an identity from making calls with the Amazon Bedrock API key, you can attach an IAM policy on an identity depending the type of key:
+ **Long-term key** – Attach the policy to the IAM user associated with the key.
+ **Short-term key** – Attach the policy to the IAM role used to generate the key.

The IAM policy that you can attach to the IAM identity is as follows:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Deny",
    "Action": "bedrock:CallWithBearerToken",
    "Resource": "*"
  }
}
```

------

### Invalidate an IAM role session
<a name="api-keys-iam-policies-invalidate-session"></a>

If a short-term key becomes compromised, you can prevent its usage by invalidating the role session that was used to generate the key. To invalidate the role session, attach the following policy to the IAM identity that generated the key. Replace *2014-05-07T23:47:00Z* with the time after which you want the session to be invalidated.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Deny",
    "Action": "*",
    "Resource": "*",
    "Condition": {
      "DateLessThan": {"aws:TokenIssueTime": "2014-05-07T23:47:00Z"}
    }
  }
}
```

------

# Control permissions for generating and using Amazon Bedrock API keys
<a name="api-keys-permissions"></a>

The generation and usage of Amazon Bedrock API keys is controlled by actions and condition keys in both the Amazon Bedrock and IAM services.

**Controlling the generation of Amazon Bedrock API keys**  
The [iam:CreateServiceSpecificCredential](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsidentityandaccessmanagementiam.html#awsidentityandaccessmanagementiam-actions-as-permissions) action controls the generation of a service-specific key (such as a long-term Amazon Bedrock API key). You can scope this action to IAM users as a resource to limit the users for which a key can be generated.

You can use the following condition keys to impose conditions on the permission for the `iam:CreateServiceSpecificCredential` action:
+ [iam:ServiceSpecificCredentialAgeDays](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#ck_ServiceSpecificCredentialAgeDays) – Lets you specify, in the condition, the key's expiration time in days. For example, you can use this condition key to only allow the creation of API keys that expire within 90 days.
+ [iam:ServiceSpecificCredentialServiceName](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#ck_ServiceSpecificCredentialAgeDays) – Lets you specify, in the condition, the name of a service. For example, you can use this condition key to only allow the creation of API keys for Amazon Bedrock and not other services.

**Controlling the usage of Amazon Bedrock API keys**  
The [bedrock:CallWithBearerToken](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonbedrock.html#amazonbedrock-actions-as-permissions) action controls the use of a short-term or long-term Amazon Bedrock API key.

You can use the `bedrock:bearerTokenType` condition key with [string condition operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String) to specify the type of bearer token for which to apply the permission for `bedrock:CallWithBearerToken`. You can specify one of the following values:
+ `SHORT_TERM` – Specifies short-term Amazon Bedrock API keys in the condition.
+ `LONG_TERM` – Specifies long-term Amazon Bedrock API keys in the condition.

The following table summarizes how to prevent an identity from generating or using Amazon Bedrock API keys:


****  

| Purpose | Long-term key | Short-term key | 
| --- | --- | --- | 
| Prevent generation of keys | Attach a policy that denies the iam:CreateServiceSpecificCredential action to an IAM identity. | N/A | 
| Prevent usage of a key | Attach a policy that denies the bedrock:CallWithBearerToken action to the IAM user associated with the key. | Attach a policy that denies the bedrock:CallWithBearerToken action to IAM identities that you don't want to be able to use the key. | 

**Warning**  
Because a short-term Amazon Bedrock API key uses existing credentials from a session, you can prevent its usage by denying the `bedrock:CallWithBearerToken` action on the identity that generated the key. However, you can't prevent generation of a short-term key.

## Example policies to control generation and usage of API keys
<a name="api-keys-permissions-examples"></a>

For example IAM policies to control the generation and usage of API keys, select from the following topics:

**Topics**
+ [

### Prevent an identity from generating long-term keys and from using Amazon Bedrock API keys
](#api-keys-permissions-examples-prevent-generation-and-use)
+ [

### Prevent an identity from using short-term API keys
](#api-keys-permissions-examples-prevent-use-short-term)
+ [

### Prevent an identity from using long-term API keys
](#api-keys-permissions-examples-prevent-use-long-term)
+ [

### Explicitly prevent an identity from using short-term API keys
](#api-keys-permissions-examples-deny-use-short-term-explicitly)
+ [

### Explicitly prevent an identity from using long-term API keys
](#api-keys-permissions-examples-deny-use-long-term-explicitly)
+ [

### Allow the creation of Amazon Bedrock keys only if they expire within 90 days
](#api-keys-permissions-examples-allow-bedrock-keys-expire-within-90-days)

### Prevent an identity from generating long-term keys and from using Amazon Bedrock API keys
<a name="api-keys-permissions-examples-prevent-generation-and-use"></a>

To prevent an IAM identity from generating long-term Amazon Bedrock API keys and using any Amazon Bedrock API keys, attach the following policy to the identity:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid":"DenyBedrockShortAndLongTermAPIKeys",
      "Effect": "Deny",
      "Action": [
        "iam:CreateServiceSpecificCredential",
        "bedrock:CallWithBearerToken"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}
```

------

**Warning**  
You can't prevent the generation of short-term keys.
This policy will prevent the creation of credentials for all AWS services that support creating service-specific credentials. For more information, see [Service-specific credentials for IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_service-specific-creds.html).

### Prevent an identity from using short-term API keys
<a name="api-keys-permissions-examples-prevent-use-short-term"></a>

To prevent an IAM identity from using short-term Amazon Bedrock API keys, attach the following policy to the identity:

### Prevent an identity from using long-term API keys
<a name="api-keys-permissions-examples-prevent-use-long-term"></a>

To prevent an IAM identity from using long-term Amazon Bedrock API keys, attach the following policy to the identity:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Deny",
            "Action": "bedrock:CallWithBearerToken",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "bedrock:bearerTokenType": "LONG_TERM"
                }
            }
        }
    ]
}
```

------

### Explicitly prevent an identity from using short-term API keys
<a name="api-keys-permissions-examples-deny-use-short-term-explicitly"></a>

To explicitly prevent an IAM identity from using short-term Amazon Bedrock API keys, but allow other API key usage, attach the following policy to the identity:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Deny",
            "Action": "bedrock:CallWithBearerToken",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "bedrock:bearerTokenType": "SHORT_TERM"
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": "bedrock:CallWithBearerToken",
            "Resource": "*"
        }
    ]
}
```

------

### Explicitly prevent an identity from using long-term API keys
<a name="api-keys-permissions-examples-deny-use-long-term-explicitly"></a>

To explicitly prevent an IAM identity from using long-term Amazon Bedrock API keys, but allow other API key usage, attach the following policy to the identity:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Deny",
            "Action": "bedrock:CallWithBearerToken",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "bedrock:bearerTokenType": "LONG_TERM"
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": "bedrock:CallWithBearerToken",
            "Resource": "*"
        }
    ]
}
```

------

### Allow the creation of Amazon Bedrock keys only if they expire within 90 days
<a name="api-keys-permissions-examples-allow-bedrock-keys-expire-within-90-days"></a>

To allow an IAM identity to create a long-term API key only if it is for Amazon Bedrock and if the expiration time is 90 days or less, attach the following policy to the identity:

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

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
       {
           "Effect": "Allow",
           "Action": "iam:CreateServiceSpecificCredential",
           "Resource": "arn:aws:iam::123456789012:user/username",
           "Condition": {
               "StringEquals": {
                   "iam:ServiceSpecificCredentialServiceName": "bedrock.amazonaws.com"
               },
               "NumericLessThanEquals": {
                   "iam:ServiceSpecificCredentialAgeDays": "90"
               }
           }
       }
   ]
}
```

------