AWS访问密钥轮换咨询:使用过期密钥是否抛异常及异常类型
Great question—let’s clarify some key points and break down your two questions clearly:
First, an important clarification: Long-term AWS Access Keys (Access Key ID + Secret Access Key) don’t have a built-in expiration date—they only become invalid if you manually disable or delete them via the IAM console/API. Temporary security credentials (like those obtained via STS) do have expiration times, though.
Here’s what happens in both scenarios:
- Long-term key is disabled/deleted:
When you attempt to call AWS APIs with such a key, you’ll get an access denied-style exception. The exact exception varies by SDK:- Python (boto3): A
botocore.exceptions.ClientErrorwith error codes likeInvalidAccessKeyId(if the key no longer exists) orAccessDenied(if the key exists but is disabled) - Java (AWS SDK v2): Subclasses of
SdkExceptionsuch asInvalidAccessKeyIdExceptionorAccessDeniedException - REST API calls directly: HTTP 403 status code, with a response body containing the relevant error code and message like "The access key ID does not exist in our records."
- Python (boto3): A
- Temporary security credentials are expired:
You’ll get an explicit "expired token" exception. For example:- Python (boto3):
ClientErrorwith error codeExpiredToken - Java (AWS SDK v2):
ExpiredTokenException
- Python (boto3):
Since long-term keys don’t expire automatically, there’s no API to "check if a key is expired"—but you can retrieve metadata to assess if it needs rotation per your organization’s policy (e.g., rotate every 90 days) or if it’s active:
Useful IAM APIs:
ListAccessKeys: Lists all access keys for a specific IAM user, including each key’sStatus(Active/Inactive) andCreateDate(when it was created). You can use the creation date to calculate if it’s time to rotate.GetAccessKeyLastUsed: Retrieves the last time the key was used to make an API call—helpful for identifying unused keys that should be rotated or deleted.
Example AWS CLI commands:
# List all access keys for a user aws iam list-access-keys --user-name YOUR_IAM_USER_NAME # Get last used details for a specific key aws iam get-access-key-last-used --access-key-id YOUR_ACCESS_KEY_ID
Example Python (boto3) code snippet:
import boto3 from datetime import datetime, timedelta iam_client = boto3.client('iam') target_user = "your-iam-user" # Fetch all access keys for the user keys_response = iam_client.list_access_keys(UserName=target_user) for key_meta in keys_response['AccessKeyMetadata']: key_id = key_meta['AccessKeyId'] status = key_meta['Status'] created_date = key_meta['CreateDate'] print(f"Key ID: {key_id} | Status: {status} | Created: {created_date.strftime('%Y-%m-%d')}") # Check if key is older than 90 days (example rotation policy) days_since_creation = (datetime.now(created_date.tzinfo) - created_date).days if days_since_creation > 90: print(f" ⚠️ This key is {days_since_creation} days old—consider rotating it") # Fetch last used time for a specific key last_used_response = iam_client.get_access_key_last_used(AccessKeyId=key_id) last_used_date = last_used_response.get('AccessKeyLastUsed', {}).get('LastUsedDate', "Never used") print(f"\nLast used date for {key_id}: {last_used_date}")
内容的提问来源于stack exchange,提问作者Swathi

