CloudFrontを経由したLambdaから別のCloudFrontに通信を行うとエラーになる

CloudFrontを経由したLambda(中身はNuxt)から、更に異なるCloudFront(またはLambda)にリクエストを送信しようとした所、以下のエラーに遭遇した。

403 ERROR
The request could not be satisfied.

We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner.
If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.

原因

CloudFront(またはLambda)は、送信元がCloudFront(またはLambda)だと上記のエラーを返すようです。
また、送信元の判別にはviaヘッダーが使用されるようです。

リクエストを確認した所、以下のようなviaヘッダーが送信されていました。
このviaヘッダーを削除してしまえば、とりあえずエラーを回避できそうです。

_header: 'GET /xxx/xxxx?xxx=xxxx HTTP/1.1\r\n' +
        (中略)
        'cloudfront-forwarded-proto: https\r\n' +
        'cloudfront-is-desktop-viewer: true\r\n' +
        'cloudfront-is-mobile-viewer: false\r\n' +
        'cloudfront-is-smarttv-viewer: false\r\n' +
        'cloudfront-is-tablet-viewer: false\r\n' +
        'cloudfront-viewer-country: US\r\n' +
        'via: 1.1 XXXX.cloudfront.net (CloudFront), 1.1 XXXX.cloudfront.net (CloudFront)\r\n' +
        'x-amz-cf-id: XXXX==\r\n' +
        'x-amzn-trace-id: Root=1-XXXX-XXXX\r\n'

対策(nuxt-axiosの場合)

nuxt-axiosの場合、以下の記述でデフォルトのヘッダーをカスタマイズ出来ます。

nuxt.config.jsに以下を記述します。

export default {
  plugins: [
    '~/plugins/axios'
  ]
}

plugins/axios.jsに以下を記述します。
ここではデフォルトのヘッダーをすべて消去しています。

export default function({ $axios }) {
    $axios.defaults.headers.common = {}
}

以上です!

コメントする