Authentication overview
AWS Polly relies on AWS Identity and Access Management (IAM) for authentication and authorization. IAM is a web service that helps you securely control access to AWS resources. When an entity, such as a user, application, or service, attempts to interact with AWS Polly, IAM verifies its identity and permissions before allowing the requested action. This model enables granular control over who can perform specific operations, such as SynthesizeSpeech or DescribeVoices, and from where they can do so. Understanding IAM is fundamental to securely integrating AWS Polly into any application or workflow.
Authentication with AWS Polly typically involves signing API requests with AWS credentials. These credentials can be long-term (access keys) or short-term (temporary security credentials provided by IAM roles). The method chosen often depends on the environment where the AWS Polly API calls are originating. For instance, applications running on AWS compute services like Amazon EC2 or AWS Lambda can leverage IAM roles for enhanced security, avoiding the need to hardcode or store long-term credentials directly within the application code. For detailed information on AWS authentication processes, consult the official AWS General Reference guide to authentication.
Supported authentication methods
AWS Polly supports several authentication methods through AWS IAM, each suited for different use cases and offering varying levels of security and operational convenience. The primary methods involve AWS access keys and IAM roles.
AWS Access Keys
AWS access keys consist of an access key ID and a secret access key. These are long-term credentials that can be used to sign programmatic requests to AWS. They are suitable for development environments, command-line interface (CLI) access, or applications running outside the AWS ecosystem where IAM roles are not directly applicable. However, due to their long-term nature, they require careful management to prevent compromise.
IAM Roles
IAM roles provide temporary security credentials that applications can use to make API requests. Instead of permanent credentials, an application assumes a role, which grants it a set of permissions for a defined period. This method is highly recommended for applications running on AWS services like Amazon EC2 instances, AWS Lambda functions, or Amazon ECS tasks. IAM roles eliminate the need to embed long-term credentials in application code or configuration files, significantly reducing the risk of credential exposure. The AWS IAM User Guide on Roles provides comprehensive details on their implementation.
Temporary Security Credentials
In addition to IAM roles, AWS also offers other ways to obtain temporary security credentials, such as federated users or through the AWS Security Token Service (STS). These credentials are short-lived and automatically expire, providing an additional layer of security compared to static access keys. They are useful for granting temporary access to users or applications without creating permanent IAM users.
Authentication Method Comparison
| Method | When to Use | Security Level |
|---|---|---|
| AWS Access Keys | AWS CLI, local development, applications outside AWS | Moderate (requires careful management) |
| IAM Roles | Applications on AWS (EC2, Lambda, ECS), cross-account access | High (temporary, no long-term credentials stored) |
| Temporary Security Credentials (STS) | Federated users, temporary access for specific tasks | High (short-lived, automatically expires) |
Getting your credentials
The process for obtaining credentials depends on the authentication method you choose. For AWS Polly, these credentials are managed through the AWS Management Console or programmatically via the AWS CLI or SDKs.
For AWS Access Keys
- Create an IAM User: Navigate to the IAM console, select 'Users', and then 'Add user'. Follow the prompts to create a new user.
- Attach Permissions: During user creation, attach an IAM policy that grants the necessary permissions for AWS Polly. For example, the
AmazonPollyReadOnlyAccessorAmazonPollyFullAccessmanaged policies. Alternatively, create a custom policy with fine-grained permissions for specific Polly actions likepolly:SynthesizeSpeech. - Generate Access Keys: After the user is created, go to the user's details page, select the 'Security credentials' tab, and then 'Create access key'. Choose 'Command Line Interface (CLI)' or 'Local code' as the use case.
- Download and Store: Download the
.csvfile containing the access key ID and secret access key. Store these credentials securely. The secret access key is only displayed once upon creation.
For detailed instructions on managing access keys, refer to the AWS IAM User Guide on Managing Access Keys.
For IAM Roles (Recommended for AWS Services)
- Create an IAM Role: In the IAM console, select 'Roles', and then 'Create role'.
- Choose a Trusted Entity: Select the AWS service that will assume this role (e.g., EC2, Lambda). This defines who can assume the role.
- Attach Permissions: Attach an IAM policy that grants the required AWS Polly permissions (e.g.,
AmazonPollyFullAccess). - Configure Trust Policy: The trust policy specifies which principals are allowed to assume the role. For an EC2 instance, this would typically allow
ec2.amazonaws.comto assume the role. - Attach Role to Resource: When launching an EC2 instance, creating a Lambda function, or configuring an ECS task, select the newly created IAM role. The underlying AWS service will automatically manage the temporary credentials for your application.
For more information on creating and using IAM roles, consult the official AWS IAM User Guide on Creating IAM roles.
Authenticated request example
This example demonstrates how to make an authenticated SynthesizeSpeech request to AWS Polly using the AWS SDK for Python (Boto3). This assumes you have configured your AWS credentials, either by setting environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN) or by using an IAM role on an AWS compute instance.
import boto3
from botocore.exceptions import ClientError
def synthesize_speech_polly(text, voice_id='Joanna', output_format='mp3', region='us-east-1'):
"""
Synthesizes speech from text using AWS Polly.
Args:
text (str): The text to synthesize.
voice_id (str): The ID of the voice to use (e.g., 'Joanna', 'Matthew').
output_format (str): The output format of the audio stream (e.g., 'mp3', 'ogg_vorbis', 'pcm').
region (str): The AWS region to use.
Returns:
bytes: The audio stream data, or None if an error occurs.
"""
try:
polly_client = boto3.client('polly', region_name=region)
response = polly_client.synthesize_speech(
Text=text,
OutputFormat=output_format,
VoiceId=voice_id
)
if "AudioStream" in response:
with response['AudioStream'] as stream:
audio_data = stream.read()
return audio_data
else:
print("Could not find AudioStream in response.")
return None
except ClientError as e:
print(f"Error synthesizing speech: {e}")
return None
except Exception as e:
print(f"An unexpected error occurred: {e}")
return None
# Example usage:
text_to_speak = "Hello, this is a test from AWS Polly, authenticated via IAM."
audio_content = synthesize_speech_polly(text_to_speak)
if audio_content:
with open('output.mp3', 'wb') as file:
file.write(audio_content)
print("Speech synthesized and saved to output.mp3")
else:
print("Failed to synthesize speech.")
In this Python example, the boto3.client('polly', region_name=region) call automatically handles the authentication process:
- If running on an EC2 instance with an attached IAM role, Boto3 will automatically use the temporary credentials provided by the instance profile.
- If running locally, Boto3 will look for credentials in environment variables, the
~/.aws/credentialsfile, or an AWS profile configured via the AWS CLI.
This abstraction simplifies the developer experience, allowing focus on application logic rather than explicit credential management for each API call. For more AWS SDK examples, refer to the AWS Polly Developer Guide on SDK examples.
Security best practices
Implementing robust security practices is critical when authenticating with AWS Polly to protect your AWS account and data. Adhering to these guidelines helps minimize the risk of unauthorized access and credential compromise.
- Use IAM Roles for AWS Services: Whenever your application runs on an AWS service (e.g., EC2, Lambda, ECS), always use IAM roles instead of long-term access keys. Roles provide temporary credentials that are automatically rotated and managed by AWS, significantly reducing the risk of exposure.
- Implement Least Privilege: Grant only the necessary permissions for AWS Polly operations. For instance, if an application only needs to convert text to speech, grant only
polly:SynthesizeSpeechpermissions, not full access. Avoid using*in IAM policies unless absolutely required. AWS provides managed policies likeAmazonPollyReadOnlyAccessorAmazonPollyFullAccess, but custom policies offer more granular control. - Regularly Rotate Access Keys: If you must use AWS access keys, rotate them regularly. This limits the window of exposure if a key is compromised. AWS recommends rotating keys at least every 90 days.
- Protect Root Account Credentials: Never use your AWS root account credentials for day-to-day operations or programmatic access. The root account has unrestricted access to all resources. Create IAM users with specific permissions for administrative tasks.
- Enable Multi-Factor Authentication (MFA): Enable MFA for your AWS root account and all IAM users, especially those with administrative privileges. MFA adds an extra layer of security by requiring a second verification method beyond just a password. The AWS IAM MFA documentation explains its benefits and setup.
- Monitor API Activity with AWS CloudTrail: Use AWS CloudTrail to log all API calls made to AWS Polly. This provides an audit trail for security analysis, operational troubleshooting, and compliance. You can identify who accessed Polly, when, and from where.
- Use Amazon CloudWatch for Alarms: Set up CloudWatch alarms to detect unusual activity, such as excessive Polly API calls from an unfamiliar IP address or attempts to use revoked credentials.
- Securely Store Credentials: If access keys are necessary for non-AWS environments, store them securely. Avoid hardcoding credentials directly in code. Use environment variables, AWS Secrets Manager, or a secure configuration management system.
- Encrypt Data in Transit: All communication with AWS Polly is encrypted in transit using TLS by default, ensuring that your text input and audio output are protected during transmission. Verify that your client-side configurations also enforce TLS 1.2 or higher. The AWS Polly Security Documentation provides further details on data protection.
- Review IAM Policies Periodically: Regularly review your IAM policies to ensure they still adhere to the principle of least privilege and remove any unnecessary permissions.