DynamoDB returns MissingAuthenticationTokenException when AWS SDK cannot find valid authentication credentials. This error occurs when your application lacks proper AWS credentials configuration, expired tokens, or incorrect region settings.
The MissingAuthenticationTokenException error in DynamoDB indicates that your application cannot authenticate with AWS services because it lacks valid credentials or authentication tokens. This error typically occurs in several scenarios: 1. **Missing credentials**: AWS SDK cannot find any credentials in the standard credential chain (environment variables, AWS credentials file, IAM roles, etc.) 2. **Expired tokens**: Temporary security credentials (from AWS STS or IAM roles) have expired 3. **Incorrect region**: The AWS region configured doesn't match the region where your DynamoDB table exists 4. **Service endpoint issues**: The endpoint URL is incorrect or points to a non-AWS service When AWS SDK makes a request to DynamoDB, it needs to sign the request with valid AWS credentials. If no credentials are found or they are invalid, DynamoDB returns HTTP status code 403 (Forbidden) with the MissingAuthenticationTokenException error.
Verify that AWS credentials are properly configured in one of the standard locations:
# Check environment variables
echo $AWS_ACCESS_KEY_ID
echo $AWS_SECRET_ACCESS_KEY
echo $AWS_SESSION_TOKEN # For temporary credentials
echo $AWS_DEFAULT_REGION
# Check AWS credentials file
cat ~/.aws/credentials
cat ~/.aws/config
# Test AWS CLI configuration
aws configure list
aws sts get-caller-identityConfiguration options:
1. Environment variables (highest priority):
export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
export AWS_DEFAULT_REGION=us-east-12. AWS credentials file (~/.aws/credentials):
[default]
aws_access_key_id = AKIAIOSFODNN7EXAMPLE
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
[production]
aws_access_key_id = AKIAI44QH8DHBEXAMPLE
aws_secret_access_key = je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY3. IAM roles for EC2, ECS, Lambda (automatic)
When creating DynamoDB client, explicitly pass credentials or profile:
// AWS SDK v3 for JavaScript
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { fromIni } from '@aws-sdk/credential-providers';
// Option 1: Explicit credentials
const client1 = new DynamoDBClient({
region: 'us-east-1',
credentials: {
accessKeyId: 'AKIAIOSFODNN7EXAMPLE',
secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
sessionToken: 'AQoEXAMPLEH4aoAH0gNCAPy...' // For temporary credentials
}
});
// Option 2: Use specific profile from credentials file
const client2 = new DynamoDBClient({
region: 'us-east-1',
credentials: fromIni({ profile: 'production' })
});
// Option 3: Use default credential chain (recommended for production)
const client3 = new DynamoDBClient({
region: process.env.AWS_REGION || 'us-east-1'
});
// Python example (boto3)
import boto3
from botocore.config import Config
# Explicit credentials
dynamodb = boto3.client(
'dynamodb',
aws_access_key_id='AKIAIOSFODNN7EXAMPLE',
aws_secret_access_key='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
region_name='us-east-1'
)
# Use profile
dynamodb = boto3.client('dynamodb', region_name='us-east-1', profile_name='production')Best practices:
- Use IAM roles for production workloads (EC2, ECS, Lambda)
- For local development, use named profiles in ~/.aws/credentials
- Never hardcode credentials in source code
Check that the IAM role or user has necessary DynamoDB permissions:
# Check current IAM identity
aws sts get-caller-identity
# List attached policies for IAM user
aws iam list-attached-user-policies --user-name YourUserName
# List attached policies for IAM role
aws iam list-attached-role-policies --role-name YourRoleName
# Test DynamoDB permissions
aws dynamodb list-tables --region us-east-1
# Minimal DynamoDB policy for basic operations
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem",
"dynamodb:Query",
"dynamodb:Scan",
"dynamodb:BatchGetItem",
"dynamodb:BatchWriteItem"
],
"Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/YourTableName"
}
]
}Common permission issues:
- IAM role not attached to EC2 instance or ECS task
- Lambda execution role missing DynamoDB permissions
- IAM policy too restrictive or missing required actions
- Cross-account access without proper trust relationship
For temporary credentials (AWS STS, IAM roles), implement token refresh logic:
// AWS SDK v3 automatically refreshes temporary credentials
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { fromTemporaryCredentials } from '@aws-sdk/credential-providers';
// Using IAM role with automatic refresh
const client = new DynamoDBClient({
region: 'us-east-1',
credentials: fromTemporaryCredentials({
params: {
RoleArn: 'arn:aws:iam::123456789012:role/YourRoleName',
RoleSessionName: 'dynamodb-session'
},
// Optional: Custom STS client configuration
clientConfig: { region: 'us-east-1' }
})
});
// Manual credential refresh example
async function refreshCredentials() {
const sts = new STSClient({ region: 'us-east-1' });
const command = new AssumeRoleCommand({
RoleArn: 'arn:aws:iam::123456789012:role/YourRoleName',
RoleSessionName: 'session-' + Date.now(),
DurationSeconds: 3600
});
const response = await sts.send(command);
return {
accessKeyId: response.Credentials.AccessKeyId,
secretAccessKey: response.Credentials.SecretAccessKey,
sessionToken: response.Credentials.SessionToken,
expiration: response.Credentials.Expiration
};
}
// Python example with boto3 session refresh
import boto3
from botocore.exceptions import ClientError
def get_fresh_session():
# boto3 automatically handles credential refresh for IAM roles
session = boto3.Session()
sts = session.client('sts')
try:
# Get fresh credentials
response = sts.assume_role(
RoleArn='arn:aws:iam::123456789012:role/YourRoleName',
RoleSessionName='dynamodb-session'
)
# Create new session with fresh credentials
return boto3.Session(
aws_access_key_id=response['Credentials']['AccessKeyId'],
aws_secret_access_key=response['Credentials']['SecretAccessKey'],
aws_session_token=response['Credentials']['SessionToken']
)
except ClientError as e:
print(f"Failed to assume role: {e}")
raiseToken management:
- Temporary credentials expire after 1 hour (default) to 12 hours (max)
- AWS SDK automatically refreshes credentials for IAM roles
- For manual STS tokens, implement refresh before expiration
- Monitor CloudTrail for AssumeRole events to track token usage
Enable AWS SDK debugging to trace credential resolution:
# Enable AWS SDK debug logging
export AWS_SDK_LOAD_CONFIG=1
export AWS_SHARED_CREDENTIALS_FILE=~/.aws/credentials
export AWS_CONFIG_FILE=~/.aws/config
export AWS_PROFILE=production # Explicitly set profile
export DEBUG=* # Node.js debug
export NODE_DEBUG=http,aws-sdk # Node.js specific
# For Java applications
export AWS_ACCESS_KEY_ID=...
export AWS_SECRET_ACCESS_KEY=...
export AWS_SESSION_TOKEN=...
export AWS_DEFAULT_REGION=us-east-1
# Test with AWS CLI debug mode
aws dynamodb list-tables --debug --region us-east-1
# Check credential provider chain
# Node.js: Add credential provider logging
import { defaultProvider } from '@aws-sdk/credential-provider-node';
import { fromNodeProviderChain } from '@aws-sdk/credential-providers';
const credentials = await fromNodeProviderChain()();
console.log('Resolved credentials:', credentials);Credential resolution order (AWS SDK):
1. Environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN
2. SSO credentials: From aws sso login cache
3. Shared credentials file: ~/.aws/credentials
4. Shared config file: ~/.aws/config
5. EC2/ECS metadata service: IAM role credentials
6. Web identity token: For EKS, AppSync, etc.
Common debugging steps:
- Check AWS_PROFILE environment variable
- Verify AWS_SDK_LOAD_CONFIG=1 is set
- Check file permissions on ~/.aws/credentials (should be 600)
- Test with AWS CLI first to isolate SDK vs configuration issues
Set up different credential strategies for development, testing, and production:
// Environment-based configuration
function createDynamoDBClient() {
const env = process.env.NODE_ENV || 'development';
const region = process.env.AWS_REGION || 'us-east-1';
switch (env) {
case 'production':
// Use IAM role (automatic)
return new DynamoDBClient({ region });
case 'staging':
// Use environment variables or instance profile
return new DynamoDBClient({ region });
case 'development':
case 'test':
// Local development with named profile
const { fromIni } = require('@aws-sdk/credential-providers');
return new DynamoDBClient({
region,
credentials: fromIni({ profile: 'dev' }),
endpoint: process.env.DYNAMODB_ENDPOINT || undefined // For local DynamoDB
});
default:
throw new Error('Unknown environment: ' + env);
}
}
// Docker/container configurationdockerfile
# Dockerfile
ENV AWS_REGION=us-east-1
ENV AWS_SDK_LOAD_CONFIG=1
yaml
# docker-compose.yml
services:
app:
environment:
- AWS_REGION=us-east-1
- AWS_SDK_LOAD_CONFIG=1
# For local development with local DynamoDB
- DYNAMODB_ENDPOINT=http://dynamodb-local:8000
yaml
# Kubernetes deployment
apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
serviceAccountName: dynamodb-access-sa # IAM role for service account (IRSA)
containers:
- name: app
env:
- name: AWS_REGION
value: us-east-1
```
Environment-specific tips:
- Local development: Use DynamoDB Local with http://localhost:8000 endpoint
- CI/CD pipelines: Use OIDC with GitHub Actions or GitLab CI
- Cross-account access: Configure IAM role trust relationships
- Multi-region: Use AWS Global Accelerator or application-level routing
## Advanced Authentication Scenarios
### AWS SDK Credential Provider Chain
The AWS SDK uses a credential provider chain that checks sources in this order:
1. Environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN
2. SSO credentials: Cached after aws sso login (supports AWS SSO, Azure AD, Okta)
3. Shared credentials file: ~/.aws/credentials (INI format)
4. Shared config file: ~/.aws/config (for SSO and assume-role)
5. EC2 Instance Metadata Service (IMDS): For EC2 instances with IAM roles
6. ECS Task Metadata: For ECS tasks with task IAM roles
7. Web Identity Token: For EKS pods with IAM roles for service accounts (IRSA)
### IAM Roles Best Practices
- EC2 instances: Use instance profiles with minimum necessary permissions
- ECS tasks: Configure task execution role and task role separately
- Lambda functions: Execution role with DynamoDB access policies
- EKS pods: Use IRSA with OIDC provider for fine-grained permissions
- Cross-account: Establish trust relationships between IAM roles
### Temporary Security Credentials
- Maximum duration: 12 hours for IAM roles, 1 hour for AWS STS by default
- Refresh strategy: AWS SDK automatically refreshes for IAM roles
- Session tokens: Required for temporary credentials, not for long-term access keys
- Security: Temporary credentials are more secure than long-term access keys
### DynamoDB Local and Mock Testing
When using DynamoDB Local or mocks, authentication is typically disabled:
// Local DynamoDB endpoint (no authentication needed)
const client = new DynamoDBClient({
region: 'local',
endpoint: 'http://localhost:8000',
credentials: {
accessKeyId: 'fake',
secretAccessKey: 'fake'
}
});### VPC Endpoints and PrivateLink
When using VPC endpoints for DynamoDB:
- No internet gateway required
- IAM policies still apply
- Endpoint policy can restrict access
- Use dynamodb.*.amazonaws.com as service name in IAM policies
### Monitoring and Alerting
Set up CloudWatch alarms for authentication failures:
- CloudTrail: Monitor AssumeRole, GetSessionToken events
- CloudWatch Metrics: UserErrors with MissingAuthenticationToken
- X-Ray: Trace credential resolution and authentication latency
- GuardDuty: Detect anomalous authentication patterns
### Security Considerations
1. Never commit credentials to version control
2. Use IAM roles over access keys whenever possible
3. Rotate access keys regularly (every 90 days recommended)
4. Implement least privilege IAM policies
5. Enable MFA for IAM users with console access
6. Use AWS Secrets Manager for credential management in applications
### Troubleshooting Tools
- aws configure list - Show current configuration
- aws sts get-caller-identity - Verify current identity
- aws iam get-user or aws iam get-role - Check IAM entity
- AWS CloudTrail - Audit API calls and authentication attempts
- AWS X-Ray - Trace distributed authentication flows
ImportConflictException: There was a conflict when attempting to import to the table
How to fix 'ImportConflictException: There was a conflict when attempting to import to the table' in DynamoDB
ResourceNotFoundException: Requested resource not found
How to fix "ResourceNotFoundException: Requested resource not found" in DynamoDB
TrimmedDataAccessException: The requested data has been trimmed
How to fix "TrimmedDataAccessException: The requested data has been trimmed" in DynamoDB Streams
GlobalTableNotFoundException: Global Table not found
How to fix "GlobalTableNotFoundException: Global Table not found" in DynamoDB
InvalidExportTimeException: The specified ExportTime is outside of the point in time recovery window
How to fix "InvalidExportTimeException: The specified ExportTime is outside of the point in time recovery window" in DynamoDB