A lightweight library for generating short-term bearer tokens for AWS Bedrock API authentication
Project description
AWS Bedrock Token Generator for Python
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 signingregion(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 invalidClientError: 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=1for 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
- Fork the repository
- Create a feature branch:
git checkout -b feature-name - Make changes and add tests
- Run tests:
pytest - Format code:
black . - Submit a pull request
Support
- Documentation: AWS Bedrock Documentation
- Issues: GitHub Issues
- AWS Support: AWS Support Center
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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file aws_bedrock_token_generator-1.0.1.tar.gz.
File metadata
- Download URL: aws_bedrock_token_generator-1.0.1.tar.gz
- Upload date:
- Size: 19.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e20b7575e09eb5e1052e3cf3760a30322ade705b56512b313c549c6ea15d1488
|
|
| MD5 |
301aa6aa96c4e7651922ecb3ce822f01
|
|
| BLAKE2b-256 |
c1007f75f3f87d565da805396925b7f3d8058744388779b5064ab682c654d92d
|
File details
Details for the file aws_bedrock_token_generator-1.0.1-py3-none-any.whl.
File metadata
- Download URL: aws_bedrock_token_generator-1.0.1-py3-none-any.whl
- Upload date:
- Size: 12.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
25d82cd7954ee57fcb0505ca89dc06f12edfb6ec310b493af3612da3c0690c58
|
|
| MD5 |
e26ef3fc1caaf5e8c81cd2e218a6798a
|
|
| BLAKE2b-256 |
ce8e5ae9c867ced667515402fc87bb72587b84998a86406660163f13a6bbcd9f
|