'How to get Cognito Identity Id in backend that is requested by AWS API Gateway?
I use AWS Cognito authentication in my web application. I have a PHP backend with REST API. After user authentication I make requests to AWS API Gateway using this library. API Gateway methods has HTTP integration type. They proxy HTTP requests to my PHP backend. How to get Cognito Identity Id in my PHP backend? I need to set a relation reference to the Cognito user in my backend.
Solution 1:[1]
API Gateway makes the caller's identity id available in the request context. Assuming you are using Cognito Identity Pool (federation) you are looking for this property: $context.identity.cognitoIdentityId
.
You could configure API Gateway to send the value of the identity id in a new header to your backend. To achieve this you have to:
- Open the integration request pane of the method configuration
- Expand the HTTP headers section and click the "Add header" link
- Give you header a name, such as
X-Cognito-Identity-Id
- In the "mapped from" field use the following expression:
context.identity.cognitoIdentityId
- Use the checkmark link on the right to save the configuration changes.
Re-deploy the API and your PHP backend should start receiving the additional header populated with the Cognito identity id from the original request.
Solution 2:[2]
For those for who the answer provided by @stefano didn't work, you can replace the context variable context.identity.cognitoIdentityId
with context.authorizer.claims.sub
.
header name: X-Cognito-User-Id
//or any name that you prefer
mapped from: context.authorizer.claims.sub
// returns cognito user id.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Stefano Buliani |
Solution 2 | Yeku Wilfred Chetat |