使用AWS Cognito调用带IAM授权的API Gateway时遇403禁止访问
Alright, let’s dig into why you’re hitting that frustrating 403 error even with full-access IAM policies and your Cognito setup in place. Here are the key areas to check and fix:
1. Fix the IAM Role Trust Relationship
Even if your roles have a * allow policy, the trust relationship is what lets Cognito actually assume those roles on behalf of your users. If this is missing or misconfigured, your user won’t get valid credentials to access the API.
For your authenticated role, update the trust policy to look like this:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Federated": "cognito-identity.amazonaws.com" }, "Action": "sts:AssumeRoleWithWebIdentity", "Condition": { "StringEquals": { "cognito-identity.amazonaws.com:aud": "us-east-1:addcched-eb42-4802-817f-700f13e51d8e" }, "ForAnyValue:StringLike": { "cognito-identity.amazonaws.com:amr": "authenticated" } } } ] }
For the unauthenticated role, just remove the ForAnyValue:StringLike condition line that checks for authenticated amr.
2. Add Explicit API Gateway Invoke Permissions
Wildcard policies (Action: "*") sometimes don’t play nicely with API Gateway’s IAM authorizer due to ARN matching quirks. Add a specific permission to your role’s policy to target your API method directly:
{ "Effect": "Allow", "Action": "execute-api:Invoke", "Resource": "arn:aws:execute-api:us-east-1:*:28p4ir5tx8/dev/GET/hello" }
You can use * for the account ID if you don’t want to hardcode it, but being explicit eliminates ARN mismatch issues.
3. Double-Check Your apig-test Command Parameters
Typos or mismatched values here are a common culprit:
- Confirm
--invoke-urlends with/dev(your stage) and doesn’t have an extra slash before/hello - Verify
--user-pool-id,--app-client-id, and--identity-pool-idmatch exactly what’s in your AWS Console (they’re case-sensitive) - Add the
--verboseflag to your command—it’ll show you the full request headers, including the signed authorization token, which can help spot issues with how the request is being authenticated.
4. Ensure Your Cognito User is Confirmed
If the user sls@test.com is still in an unconfirmed state (e.g., hasn’t verified their email address), Cognito won’t issue valid access tokens. Head to the AWS Console > Cognito > Your User Pool > Users and check the user’s status. If they’re unconfirmed, resend the verification code or manually confirm them to test.
5. Verify API Gateway Stage & Method Settings
Quick sanity check:
- Make sure your
devstage in API Gateway has IAM authorization enabled (your Serverless config should set this, but it’s worth confirming) - Check if there are any other authorizers, request validators, or WAF rules attached to the
/hellomethod that might be blocking the request unexpectedly.
内容的提问来源于stack exchange,提问作者F. Panoski

