无需JS SDK获取DynamoDB受限IAM凭证的HTTP调用问题
Let's break this down clearly for you:
1. Is using GetCredentialsForIdentity the right approach?
Absolutely! This is exactly the correct method for fetching temporary, restricted IAM credentials tied to a Cognito Identity ID without relying on the AWS SDK. It fits perfectly with your goal of keeping your web app lightweight while still accessing DynamoDB securely. The method validates the provided identity (via login tokens for authenticated users) and returns STS-backed credentials mapped to your identity pool's IAM roles.
2. What's the correct HTTP endpoint?
The endpoint you tested—https://cognito-identity.us-east-1.amazonaws.com—is actually the correct one for the us-east-1 region. Your 400 error isn't due to the wrong endpoint; it's because your request is missing critical parameters.
Why you're getting a 400 error
If your Identity ID is linked to an authenticated user (e.g., from a Cognito User Pool), you must include the Logins parameter in your request body to prove you own that identity. Without this, AWS can't verify the identity and returns a Bad Request.
Corrected request examples
For authenticated users (Cognito User Pool)
Add the Logins object with your user pool's issuer URL and the user's ID token:
fetch('https://cognito-identity.us-east-1.amazonaws.com', { method: 'POST', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'AWSCognitoIdentityService.GetCredentialsForIdentity', }, body: JSON.stringify({ "IdentityId": "us-east-1:<GUID of the user>", "Logins": { "cognito-idp.us-east-1.amazonaws.com/<YOUR-USER-POOL-ID>": "<USER-ID-TOKEN>" } }) });
For anonymous identities (if enabled in your identity pool)
If you're using an unauthenticated/anonymous Identity ID, you can omit the Logins parameter—but first ensure your identity pool has anonymous access enabled:
fetch('https://cognito-identity.us-east-1.amazonaws.com', { method: 'POST', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'AWSCognitoIdentityService.GetCredentialsForIdentity', }, body: JSON.stringify({ "IdentityId": "us-east-1:<ANONYMOUS-GUID>" }) });
Quick key notes
- Replace
<YOUR-USER-POOL-ID>with your actual Cognito User Pool ID (e.g.,us-east-1_abc123XYZ). - The
X-Amz-Targetheader you used is correct—don't modify it. - Double-check that your identity pool's IAM roles have the specific DynamoDB permissions your app needs.
内容的提问来源于stack exchange,提问作者Vitaly Zdanevich

