登录后如何用boto3通过授权码从Amazon Cognito获取用户详情?
No worries, let's break this down step by step—this is a common flow with Cognito's authorization code grant, and boto3 has all the tools you need once you know the right methods to call.
Prerequisites First
Before writing code, make sure you have these values handy:
- Your Cognito User Pool ID
- Your App Client ID (from the User Pool's App Clients section)
- App Client Secret (only if your app client is marked as "Confidential"—skip this for public clients like SPAs)
- The authorization code from your redirect URL
- The exact redirect URI you configured in your app client (must match what you used to get the code)
Step 1: Set Up the boto3 Cognito Client
First, initialize the Cognito Identity Provider client with your AWS region:
import boto3 # Replace 'us-east-1' with your actual AWS region cognito_client = boto3.client('cognito-idp', region_name='us-east-1')
Step 2: Exchange the Authorization Code for Tokens
Use the initiate_auth method with the AUTHORIZATION_CODE flow to swap your code for access, ID, and refresh tokens.
For Public App Clients (No Secret):
token_response = cognito_client.initiate_auth( ClientId='your-app-client-id', AuthFlow='AUTHORIZATION_CODE', AuthParameters={ 'CODE': '667f8988-aabc-494e-a8b0-0dc0d47057ab', # Your authorization code 'REDIRECT_URI': 'http://localhost:5000/aws_cognito_redirect' # Exact match to your client config } )
For Confidential App Clients (With Secret):
You'll need to generate a SecretHash using your client ID, client secret, and the user's username (you might need to track the username from your login flow, or extract it later from the ID token). Here's how to calculate it:
import hmac import hashlib import base64 def generate_secret_hash(client_id, client_secret, username): message = bytes(f"{username}{client_id}", 'utf-8') secret_key = bytes(client_secret, 'utf-8') return base64.b64encode(hmac.new(secret_key, message, digestmod=hashlib.sha256).digest()).decode() # Add SecretHash to the AuthParameters token_response = cognito_client.initiate_auth( ClientId='your-app-client-id', AuthFlow='AUTHORIZATION_CODE', AuthParameters={ 'CODE': '667f8988-aabc-494e-a8b0-0dc0d47057ab', 'REDIRECT_URI': 'http://localhost:5000/aws_cognito_redirect', 'SECRET_HASH': generate_secret_hash('your-app-client-id', 'your-app-client-secret', 'user-username') } )
Step 3: Fetch User Details with the Access Token
Once you have the access token from the token response, use the get_user method to pull the user's profile data:
access_token = token_response['AuthenticationResult']['AccessToken'] user_profile = cognito_client.get_user( AccessToken=access_token ) # Print or process the user data print("User Details:") print(f"Username: {user_profile['Username']}") print("User Attributes:") for attr in user_profile['UserAttributes']: print(f"- {attr['Name']}: {attr['Value']}")
Key Notes to Avoid Headaches
- Authorization Code One-Time Use: The code can only be exchanged once—if you get an error about an expired or used code, you'll need to send the user back to login to get a new one.
- Exact Redirect URI: Even a tiny difference (like trailing slash, http vs https) will cause an error. Double-check it matches what's in your Cognito app client settings.
- Error Handling: Wrap your calls in try-except blocks to catch common issues like
ExpiredCodeException,CodeMismatchException, orInvalidParameterException.
内容的提问来源于stack exchange,提问作者Ranjith Ramachandra

