- Newest
- Most votes
- Most comments
The 401 Unauthorized error you're encountering when calling your POST REST API through API Gateway integrated with Cognito could be due to a few reasons:
-
Token Type Mismatch: You're using the ID token for authorization, but the API might be configured to expect an access token instead. Cognito uses different token types for different purposes. The ID token is primarily used for authentication, while the access token is used for authorization.
-
OAuth Scopes Configuration: If your API is set up to use access tokens, the OAuth Scopes option in the API Gateway console might be misconfigured. For access token authorization, you need to properly configure the OAuth Scopes. If you're using ID tokens, the OAuth Scopes should be left blank.
-
Authorizer Configuration: Ensure that your Cognito authorizer is correctly set up in API Gateway. Double-check that the user pool and app client settings in API Gateway match those in your Cognito configuration.
-
Token Expiration: Verify that the token you're using hasn't expired. Tokens have a limited lifetime, and using an expired token will result in a 401 error.
To troubleshoot this issue:
-
Check your API Gateway configuration to confirm whether it's set up for ID tokens or access tokens.
-
If using access tokens, ensure the OAuth Scopes are correctly configured in the API Gateway console.
-
Verify that the Cognito authorizer settings in API Gateway are correct and match your Cognito user pool configuration.
-
Try using an access token instead of an ID token in your API calls. You may need to adjust your authentication flow to request and use the appropriate token type.
-
Check the token's expiration and ensure you're using a fresh, valid token for each request.
-
Review your Cognito user pool settings, particularly the app client configuration, to ensure it's set up correctly for the type of authorization you're attempting.
If the issue persists after checking these points, you may want to enable more detailed logging in API Gateway and Cognito to get more information about the authorization process and any specific errors occurring.
Sources
Create and troubleshoot Cognito and API Gateway integrations | AWS re:Post
Configuring machine to machine Authentication with Amazon Cognito and Amazon API Gateway – Part 2 | AWS Cloud Operations & Migrations Blog
Relevant content
- asked a year ago
- Accepted Answerasked 3 years ago
- Accepted Answerasked 3 years ago
- AWS OFFICIALUpdated 3 months ago
- AWS OFFICIALUpdated a year ago
- AWS OFFICIALUpdated 2 months ago
- AWS OFFICIALUpdated a month ago
I have tried all the suggestions but I am still getting the 401 error.
Something I tried and it worked, when I removed the Cognito integration option in the API Gateway request method, my lambda function was called, the token was validated and returned status 200. Anyway, I still don't understand why this integration with Cognito doesn't work.