Unable to add X-forwarded-for header in https api gateway

0

I am using HTTPS Api gateway to add a proxy and then add this proxy to a CloudFront distribution to allow HTTP to HTTPS redirect. I would like to get the "X-forwarded-for" header. I have already enabled "allow all headers" in the cache settings for CloudFront. I have also configured the CORS policy to allow all headers at the HTTPS API gateway. I am still unable to get the X-forwarded-for header in the response. Is there a way I can add this header?

2 Answers
1

Hi,
let me know if I understood your problem correctly: https://imgur.com/a/EH85bg6. I assume also that you're using HTTP API Gateway. If so, you should have the IP of the requester in two places:
event.headers.x-forwarded-for: "<requester-ip>,<cloudfront-ip>" Please note, that this value is comma-separated.
event.requestContext.http.sourceIp: "<requester-ip>"

If you need some reference, here is a sample event, that I generated to reproduce your issues.

{
"version": "2.0",
"routeKey": "GET /",
"rawPath": "/",
"rawQueryString": "",
"headers": {
"accept-encoding": "br,gzip",
"content-length": "0",
"host": "<api-gw-uri>",
"user-agent": "Amazon CloudFront",
"via": "2.0 <cloudfront-ip> (CloudFront)",
"x-amz-cf-id": "",
"x-amzn-trace-id": "",
"x-forwarded-for": "<requester-ip>,<cloudfront-ip>",
"x-forwarded-port": "443",
"x-forwarded-proto": "https"
},
"requestContext": {
"accountId": "<account-id>",
"apiId": "<api-id>",
"domainName": "<api-domainname>",
"domainPrefix": "<api-domain-prefix>",
"http": {
"method": "GET",
"path": "/",
"protocol": "HTTP/1.1",
"sourceIp": "<requester-ip>",
"userAgent": "Amazon CloudFront"
},
"requestId": "",
"routeKey": "GET /",
"stage": "$default",
"time": "05/Apr/2022:20:17:43 +0000",
"timeEpoch": 1649189863166
},
"isBase64Encoded": false
}

Let me know if it is solving your problem.
Regards, Dominik

answered 2 years ago
0

You can find a good explanation here. The summary is that, x-forwarded-for was a de-facto-standard and now the standard header is forwarded. If the request already contains x-forwarded-for header, API Gateway will put it in Forwarded header. But still Load Balancer uses x-forwarded-for header. So if you look at your incoming request after API-Gateway and Load Balancer, you will see the IP address of your API Gateway in x-forwarded-for header and the IP addresses of you client in Forwarded header.

Mojtaba
answered 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions