如何验证Amazon SessionToken/Cognito凭证?开发者认证身份流场景
Got it, let's walk through how to effectively validate those credentials for your proof-of-concept—since you don't need to access a resource like S3, we can use a purpose-built AWS API to confirm validity directly.
1. Use the STS GetCallerIdentity API
The simplest and most reliable way to validate credentials is to call the GetCallerIdentity API from AWS STS. This API doesn't require any special permissions (as long as the credentials are valid) and returns core identity details you can cross-check against your expectations.
Example Code (Python)
Here's a quick snippet to implement this:
import boto3 def validate_sts_credentials(access_key, secret_key, session_token): sts_client = boto3.client( 'sts', aws_access_key_id=access_key, aws_secret_access_key=secret_key, aws_session_token=session_token ) try: identity = sts_client.get_caller_identity() # Add your custom validation logic here print(f"Credentials are valid. Associated identity ARN: {identity['Arn']}") return True, identity except Exception as e: # Catch errors like expired tokens, invalid keys, etc. print(f"Credentials invalid: {str(e)}") return False, None
2. Add Custom Validation Checks
Once you get the identity response, you should verify it matches what you expect from your AssumeRoleWithWebIdentity call:
- Confirm the ARN matches the IAM role you specified in your
AssumeRoleWithWebIdentityrequest - Check that the Account ID is your AWS account number
- If needed, cross-reference the UserId with the authenticated user in your system
3. Handle Common Edge Cases
- Expired credentials:
GetCallerIdentitywill throw an error if the session token has expired—this lets you detect when you need to refresh credentials - Access denied: While rare, if the credentials don't have permission to call
GetCallerIdentity(unlikely for valid session credentials), this still signals the credentials are structured correctly but lack basic permissions
Why This Is Better Than Resource Access
Unlike testing access to S3 or another service, GetCallerIdentity is designed specifically to validate identity and credential validity without requiring resource-specific permissions. It's lightweight, fast, and directly answers your core question: "Are these credentials valid and tied to the expected identity?"
内容的提问来源于stack exchange,提问作者MichaelChan

