Simplify and Secure Your Amazon Bedrock API Access with Short-Term Keys

Niranjan GNiranjan G
6 min read

Amazon Bedrock is revolutionizing how developers build generative AI applications by providing easy access to powerful foundation models. To interact with these models via the Amazon Bedrock API, you need to authenticate using API keys. Amazon Bedrock offers two types of API keys: short-term and long-term. In this blog post, we’ll explore why short-term API keys are the preferred choice for securing your applications, particularly in production environments, and provide a step-by-step guide to implementing them.

Understanding Amazon Bedrock API Keys

API keys are credentials that authenticate your identity when making requests to the Amazon Bedrock API. They ensure that only authorized users or applications can access the service. Amazon Bedrock provides two types of API keys:

  • Short-term API keys: These keys are generated based on an AWS Identity and Access Management (IAM) role and are valid for the duration of your session, up to a maximum of 12 hours. They are ideal for production environments because they can be automatically refreshed, enhancing security.

  • Long-term API keys: These keys are simpler to set up and can last for a specified period, such as 30 days. They are designed for exploration and development but are not recommended for production due to potential security risks.

The choice between short-term and long-term keys depends on your use case, but for production applications, short-term keys are generally considered the more secure option.

Why Choose Short-Term API Keys?

Short-term API keys offer several advantages that make them the preferred choice for securing your Amazon Bedrock applications:

  1. Enhanced Security: Short-term keys expire quickly, typically within 12 hours, which significantly reduces the window for potential misuse. If a key is compromised, it will stop working soon, limiting the risk of unauthorized access.

  2. Automatic Credential Rotation: You can configure your application to automatically generate new short-term keys when they expire. This ensures continuous access without requiring manual intervention, which is critical for production environments.

  3. Fine-Grained Control: Short-term keys inherit the permissions of the IAM role used to generate them. This allows you to precisely control what actions can be performed with the key, adhering to the principle of least privilege.

These benefits make short-term keys a robust choice for developers building secure, scalable applications with Amazon Bedrock.

How to Generate Short-Term API Keys

To use short-term API keys, you need an IAM role with the appropriate permissions to access Amazon Bedrock. Below is a step-by-step guide to generating and managing short-term API keys programmatically.

Step 1: Set Up an IAM Role

Create an IAM role that has permissions to access Amazon Bedrock. This role should be configured to allow your application or service to assume it. Ensure the role has the necessary policies, such as AmazonBedrockFullAccess or a custom policy tailored to your needs.

Step 2: Generate and Refresh Short-Term API Keys

You can use the AWS SDK to assume the IAM role and generate a short-term API key. The following Python script demonstrates how to generate a short-term key and refresh it when it expires:

from datetime import datetime, timedelta
import os
import boto3
from botocore.credentials import Credentials
from aws_bedrock_token_generator import BedrockTokenGenerator

# Configuration
SESSION_DURATION = timedelta(hours=12)  # Maximum session duration is 12 hours
EFFECTIVE_TOKEN_DURATION = min(SESSION_DURATION, timedelta(hours=12))
ROLE_ARN = "arn:aws:iam::111122223333:role/TargetRole"  # Replace with your role ARN
ROLE_SESSION_NAME = "your-session-name"
REGION = "us-east-1"  # Replace with your region

def get_session_from_assume():
    sts = boto3.client("sts")
    response = sts.assume_role(
        RoleArn=ROLE_ARN,
        RoleSessionName=ROLE_SESSION_NAME,
        DurationSeconds=int(SESSION_DURATION.total_seconds())
    )
    creds = response["Credentials"]
    return Credentials(
        access_key=creds["AccessKeyId"],
        secret_key=creds["SecretAccessKey"],
        token=creds["SessionToken"]
    )

# Generate initial token
generator = BedrockTokenGenerator()
creds = get_session_from_assume()
token = generator.get_token(creds, region=REGION)
token_created_at = datetime.utcnow()

# Function to refresh token if expired
def refresh_token():
    global token, token_created_at
    if datetime.utcnow() - token_created_at >= EFFECTIVE_TOKEN_DURATION:
        creds = get_session_from_assume()
        token = generator.get_token(creds, region=REGION)
        token_created_at = datetime.utcnow()
    return token

# Set the token as an environment variable
os.environ['AWS_BEARER_TOKEN_BEDROCK'] = refresh_token()

This script uses the aws_bedrock_token_generator package to generate a short-term API key and sets it as an environment variable (AWS_BEARER_TOKEN_BEDROCK) for use in API calls. The refresh_token function checks if the token has expired and generates a new one if necessary, ensuring uninterrupted access.

Step 3: Use the API Key

Once the token is set as an environment variable, you can use it to authenticate API requests to Amazon Bedrock. For example, you can make a simple API call to the converse endpoint:

import boto3

# Create the Bedrock client
client = boto3.client(
    service_name="bedrock-runtime",
    region_name="us-east-1"
)

# Define the model and message
model_id = "us.anthropic.claude-3-5-haiku-20241022-v1:0"
messages = [{"role": "user", "content": [{"text": "Hello! Can you tell me about Amazon Bedrock?"}]}]

# Make the API call
response = client.converse(
    modelId=model_id,
    messages=messages,
)

# Print the response
print(response['output']['message']['content'][0]['text'])

This code snippet demonstrates how to use the generated short-term API key to interact with Amazon Bedrock’s models.

Warning: Avoid Long-Term Keys in Production

While long-term API keys are convenient for getting started with Amazon Bedrock, they pose significant security risks in production environments. Since they can last for extended periods (e.g., 30 days), a compromised long-term key could grant unauthorized access for a prolonged time. AWS strongly advises against using long-term keys in production. Instead, opt for short-term keys or other temporary credential solutions, such as IAM roles or AWS Security Token Service (STS) credentials.

For exploration and development, long-term keys can be generated quickly through the AWS Management Console:

  1. Sign in to the AWS Management Console and open the Amazon Bedrock console.

  2. Navigate to the API keys section and select the Long-term API keys tab.

  3. Choose Generate long-term API keys, select an expiration period (e.g., 30 days), and generate the key.

  4. Copy and securely store the key, as it will only be displayed once.

However, once you’re ready to move to production, transitioning to short-term keys or other secure authentication methods is essential.

Comparison of Short-Term and Long-Term API Keys

FeatureShort-Term API KeysLong-Term API Keys
DurationUp to 12 hoursUp to 30 days or more
SecurityHigh (expires quickly)Lower (longer exposure if compromised)
Use CaseProduction environmentsExploration and development
Permission ControlInherits IAM role permissionsLimited to basic API requests
Automatic RefreshSupportedNot supported

This table highlights why short-term keys are better suited for production, offering greater security and flexibility.

Additional Resources

To deepen your understanding of Amazon Bedrock and API key management, explore the following resources:

Conclusion

Securing your Amazon Bedrock API access is critical for protecting your applications and data. Short-term API keys provide a secure and manageable way to authenticate your API requests, making them the ideal choice for production environments. By implementing short-term keys, you can ensure that your credentials are rotated frequently, reducing the risk of security breaches. While long-term keys are useful for initial exploration, transitioning to short-term keys or other secure authentication methods is recommended for ongoing use.

By following these best practices, you can build secure and scalable AI applications with Amazon Bedrock, leveraging its powerful capabilities with confidence.

0
Subscribe to my newsletter

Read articles from Niranjan G directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Niranjan G
Niranjan G

I am a persistent and detail-oriented cybersecurity professional, boasting over 19+w years of dedicated experience in the field.