Skip to main content

A lightweight library for generating short-term bearer tokens for AWS Bedrock API authentication

Project description

AWS Bedrock Token Generator for Python

Build Status PyPI version Python versions Apache 2.0 License

The AWS Bedrock Token Generator for Python is a lightweight utility library that generates short-term bearer tokens for AWS Bedrock API authentication. This library simplifies the process of creating secure, time-limited tokens that can be used to authenticate with AWS Bedrock services without exposing long-term credentials.

Features

  • Simple API: Single method to generate bearer tokens
  • Secure: Uses AWS SigV4 signing with 12-hour token expiration
  • Multi-region support: Works with any AWS region where Bedrock is available
  • Boto3 Integration: Seamlessly works with boto3 credential providers
  • Lightweight: Minimal dependencies, focused functionality
  • Well-tested: Comprehensive unit tests with multiple scenarios
  • Type hints: Full type annotation support for better IDE experience

Installation

Using pip

pip install aws-bedrock-token-generator

From source

git clone https://github.com/aws/aws-bedrock-token-generator-python.git
cd aws-bedrock-token-generator-python
pip install -e .

Quick Start

Basic Usage

from aws_bedrock_token_generator import BedrockTokenGenerator
import boto3

# Create token generator
token_generator = BedrockTokenGenerator()

# Generate token using default credentials
session = boto3.Session()
credentials = session.get_credentials()

bearer_token = token_generator.get_token(credentials, "us-west-2")

# Use the token for API calls (valid for 12 hours)
print(f"Bearer Token: {bearer_token}")

API Reference

BedrockTokenGenerator

get_token(credentials, region)

Generates a bearer token for AWS Bedrock API authentication.

Parameters:

  • credentials (botocore.credentials.Credentials): AWS credentials to use for signing
  • region (str): AWS region identifier (e.g., "us-west-2")

Returns:

  • str: A bearer token valid for 12 hours, prefixed with "bedrock-api-key-"

Raises:

  • ValueError: If credentials or region are invalid
  • ClientError: If AWS service call fails

Example:

from aws_bedrock_token_generator import BedrockTokenGenerator
import boto3

generator = BedrockTokenGenerator()
session = boto3.Session()
credentials = session.get_credentials()
token = generator.get_token(credentials, "us-west-2")

Token Format

The generated tokens follow this format:

bedrock-api-key-<base64-encoded-presigned-url>&Version=1
  • Prefix: bedrock-api-key- identifies the token type
  • Payload: Base64-encoded presigned URL with embedded credentials
  • Version: &Version=1 for future compatibility
  • Expiration: 12 hours from generation time

Security Considerations

  • Token Expiration: Tokens are valid for 12 hours and cannot be renewed
  • Secure Storage: Store tokens securely and avoid logging them
  • Credential Management: Use IAM roles and temporary credentials when possible
  • Network Security: Always use HTTPS when transmitting tokens
  • Principle of Least Privilege: Ensure underlying credentials have minimal required permissions

Requirements

  • Python: 3.7 or later
  • boto3: 1.26.0 or later
  • botocore: 1.29.0 or later

Examples

Complete Example with Error Handling

from aws_bedrock_token_generator import BedrockTokenGenerator
import boto3
from botocore.exceptions import ClientError, NoCredentialsError

def generate_bedrock_token():
    try:
        token_generator = BedrockTokenGenerator()
        
        # Get credentials from default credential chain
        session = boto3.Session()
        credentials = session.get_credentials()
        
        if not credentials:
            raise NoCredentialsError()
        
        token = token_generator.get_token(credentials, "us-west-2")
        
        print(f"Successfully generated token: {token[:30]}...")
        return token
        
    except NoCredentialsError:
        print("Error: No AWS credentials found")
    except ClientError as e:
        print(f"AWS service error: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")

if __name__ == "__main__":
    generate_bedrock_token()

Integration with AWS Bedrock Client

import boto3
from aws_bedrock_token_generator import BedrockTokenGenerator

# Generate token
token_generator = BedrockTokenGenerator()
session = boto3.Session()
credentials = session.get_credentials()
bearer_token = token_generator.get_token(credentials, "us-west-2")

# Use with Bedrock client (conceptual - actual implementation may vary)
bedrock_client = boto3.client('bedrock', region_name='us-west-2')
# Note: Token usage with Bedrock client depends on specific API requirements

Development

Setting up Development Environment

# Clone the repository
git clone https://github.com/aws/aws-bedrock-token-generator-python.git
cd aws-bedrock-token-generator-python

# Install in development mode with dev dependencies
pip install -e .[dev]

Running Tests

# Run all tests
pytest

# Run tests with coverage
pytest --cov=aws_bedrock_token_generator

# Run tests with verbose output
pytest -v

Code Quality

# Format code with black
black aws_bedrock_token_generator tests

# Check code style with flake8
flake8 aws_bedrock_token_generator tests

# Type checking with mypy
mypy aws_bedrock_token_generator

Building Distribution

# Build wheel and source distribution
python -m build

# Install from local build
pip install dist/aws_bedrock_token_generator-*.whl

Contributing

We welcome contributions! Please see CONTRIBUTING.md for details on how to contribute to this project.

Development Workflow

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature-name
  3. Make changes and add tests
  4. Run tests: pytest
  5. Format code: black .
  6. Submit a pull request

Support

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Related Projects

Changelog

See CHANGELOG.md for a list of changes and version history.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aws_bedrock_token_generator-1.0.1.tar.gz (19.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

aws_bedrock_token_generator-1.0.1-py3-none-any.whl (12.0 kB view details)

Uploaded Python 3

File details

Details for the file aws_bedrock_token_generator-1.0.1.tar.gz.

File metadata

File hashes

Hashes for aws_bedrock_token_generator-1.0.1.tar.gz
Algorithm Hash digest
SHA256 e20b7575e09eb5e1052e3cf3760a30322ade705b56512b313c549c6ea15d1488
MD5 301aa6aa96c4e7651922ecb3ce822f01
BLAKE2b-256 c1007f75f3f87d565da805396925b7f3d8058744388779b5064ab682c654d92d

See more details on using hashes here.

File details

Details for the file aws_bedrock_token_generator-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for aws_bedrock_token_generator-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 25d82cd7954ee57fcb0505ca89dc06f12edfb6ec310b493af3612da3c0690c58
MD5 e26ef3fc1caaf5e8c81cd2e218a6798a
BLAKE2b-256 ce8e5ae9c867ced667515402fc87bb72587b84998a86406660163f13a6bbcd9f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page