Reputation: 1671
I have setup a CloudFront Distribution with an API Gateway as one of the origins and this API Gateway is configured with an AWS IAM authorizer.
When CloudFront url is invoked with Authorization headers, it returns a 403 error.
{
"message": "Missing Authentication Token"
}
However, when the API Gateway url is invoked instead of CloudFront url with the same Authorization headers, it worked.
I've also tried invoking the endpoint without any authorizer via CloudFront url and it worked. Any idea on how to solve this issue.
Upvotes: 9
Views: 13624
Reputation: 317
Please see below, in case if anyone is facing this issue when using API Gateway as a secondary origin - behavior instead of default behavior for the Cloudfront Distribution i.e.
/api/*
requests to API Gateways3
or other default resource like an Application load balancerI was using AWS CDK to define and deploy AWS API Gateway as a secondary behavior and faced the same issue and I did everything including
My configuration for the deployment is as follows:
originConfigs: [{
customOriginSource: {
domainName: clientAppBucket.bucketWebsiteDomainName,
originProtocolPolicy: cloudfront.OriginProtocolPolicy.HTTP_ONLY
},
behaviors: [{
isDefaultBehavior: true,
compress: true
}]
},
{
customOriginSource: { domainName: `${api.restApiId}.execute-api.${this.region}.amazonaws.com/prod` },
behaviors: [
{
pathPattern: "/api/*",
allowedMethods: cloudfront.CloudFrontAllowedMethods.ALL,
defaultTtl: cdk.Duration.seconds(0),
forwardedValues: {
queryString: true,
headers: ["Authorization"],
},
},
],
}]
The problem was that Cloudfront prepends the path that we are using as a custom behavior with each request i.e. when we call domain.com/api/something
, It will not call ${api.restApiId}.execute-api.${this.region}.amazonaws.com/
prod/something. Instead it will call ${api.restApiId}.execute-api.${this.region}.amazonaws.com
/prod/api/something.
Therefore, either the stage name of the default API Gateway URL which is usually prod
should be equal to the behavior path which we specify i.e /path/*
or /api/*
or /backend/*
etc -> /prod/*
or we should have a /path/
as a resource at the top level of RestApi and nest all the resources under it
Upvotes: 5
Reputation: 178956
When provisioning a CloudFront distribution, remember that CloudFront removes most headers from the request by default.
This is done to optimize the cache hit ratio while preventing your origin server from making decisions based on those headers that would not be appropriate for different requests based on other variations (or absence) of those headers, which CloudFront would then serve from cache, inappropriately.
You'll need to whitelist the Authorization
header for forwarding to the origin.
Note also that when provisioning API Gateway behind a CloudFront distribution that you control, you'll probably want to deploy your API endpoint as regional and not edge-optimized.
Upvotes: 9