0
0
AwsDebug / FixBeginner · 4 min read

How to Fix Invalid Security Token Error in AWS

The Invalid security token error in AWS happens when your credentials or session token are missing, expired, or incorrect. To fix it, refresh your AWS credentials or session token and ensure your environment variables or configuration files are correctly set.
🔍

Why This Happens

This error occurs because AWS cannot verify your identity due to an invalid or expired security token. This usually happens when temporary credentials expire, environment variables are incorrect, or the AWS CLI/SDK is using outdated tokens.

python
import boto3

# Using expired session token
session = boto3.Session(
    aws_access_key_id='AKIA...EXAMPLE',
    aws_secret_access_key='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
    aws_session_token='ExpiredOrInvalidToken'
)
s3 = session.client('s3')
s3.list_buckets()
Output
botocore.exceptions.ClientError: An error occurred (InvalidClientTokenId) when calling the ListBuckets operation: The security token included in the request is invalid.
🔧

The Fix

Update your AWS credentials by refreshing your session token or reconfiguring your AWS CLI with valid credentials. Make sure environment variables like AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN are current and correctly set.

python
import boto3

# Using valid refreshed session token
session = boto3.Session(
    aws_access_key_id='AKIA...VALID',
    aws_secret_access_key='ValidSecretKey',
    aws_session_token='ValidSessionToken'
)
s3 = session.client('s3')
response = s3.list_buckets()
print([bucket['Name'] for bucket in response['Buckets']])
Output
["example-bucket-1", "example-bucket-2"]
🛡️

Prevention

  • Use AWS CLI commands like aws configure to set credentials properly.
  • Regularly refresh temporary credentials if using roles or federated access.
  • Check environment variables and config files for outdated tokens.
  • Use AWS SDKs that automatically refresh tokens when possible.
⚠️

Related Errors

  • ExpiredToken: Happens when your session token has expired; fix by renewing credentials.
  • AccessDenied: Occurs when permissions are insufficient; check IAM policies.
  • UnrecognizedClientException: Usually caused by wrong access keys; verify keys are correct.

Key Takeaways

Always keep your AWS credentials and session tokens up to date to avoid invalid token errors.
Use AWS CLI or SDK tools to manage and refresh credentials automatically when possible.
Check environment variables and config files for outdated or incorrect tokens before running AWS commands.
Temporary credentials expire and must be refreshed regularly if you use roles or federated access.
Understand related errors like ExpiredToken and AccessDenied to troubleshoot AWS authentication issues quickly.