Cloudfront, reverse proxy question

I’ve been asked to use AWS Cloudfront in front of Keycloak.

The setup is:

Cloudfront -> ALB -> ECS Fargate (2x keycloak)

I’ve setup Cloudfront to forward the host header, and not cache for /auth/admin* and /auth/realms/*.

I’m doing some debugging on the request headers that make it to Keycloak.

  • when hitting the ALB directly:
{
  "Host": [
    "host.foo.bar"
  ],
  "X-Forwarded-For": [
    "82.64.214.156"
  ],
  "X-Amzn-Trace-Id": [
    "Root=1-61b9eba3-68d9df4826fd20125b7f07c3"
  ],
  "user-agent": [
    "curl/7.77.0"
  ],
  "accept": [
    "*/*"
  ],
  "X-Forwarded-Port": [
    "443"
  ],
  "X-Forwarded-Proto": [
    "https"
  ]
}
  • when hitting the cloudfront distribution:
{
  "X-Forwarded-Proto": [
    "https"
  ],
  "Via": [
    "2.0 b59465a36dda3b4ec573f7a87861306c.cloudfront.net (CloudFront)"
  ],
  "X-Amz-Cf-Id": [
    "-1XMfUKyaV6iqnCj20jHappmkwSHxy1bOH7hDBhq3X5wRjSqf2yH5A=="
  ],
  "X-Forwarded-For": [
    "2a01:e0a:36c:e260:6874:8d9a:412a:675b, 64.252.114.52"
  ],
  "Host": [
    "xxxxxxxxxx.cloudfront.net"
  ],
  "X-Forwarded-Port": [
    "443"
  ],
  "User-Agent": [
    "Amazon CloudFront"
  ],
  "X-Amzn-Trace-Id": [
    "Root=1-61b9ebbd-7fc5826510ad113f0f27eeb3"
  ]
}

When I use the ALB endpoint, I have no problems. But when I use the Cloudfront endpoint, I get an invalid request error (with nothing else in the logs):

[2021-12-15T14:24:53+01:00] (web/web/23d049a4c0a846c28c367fbd448be3fe) 13:24:53,463 WARN  [org.keycloak.events] (default task-1) type=LOGIN_ERROR, realmId=master, clientId=null, userId=null, ipAddress=2a01:e0a:36c:e260:6874:8d9a:412a:675b, error=invalid_request

Any ideas what I’m missing? Is there another header that needs to be forwarded?

Do not forget to create separate custom cache policy for CF, containing next headers:

  • Authorization
  • Host
  • Origin
  • CloudFront-Forwarded-Proto

After that you have to attach it to CF keycloak behavior.
If you will see caching issues - try to reduce Max and Default TTL to e.g. 30. Min TTL should be 0.
Probably, also worth to turn off Gzip.

1 Like