3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

やりたいこと

API GatewayをAPI Keyで認証かけた時に、認証されたAPI Keyの値をLambda側で扱いたい。

Lambdaにくる値のイメージ

API Gateway Proxyで実装するとこんな値がきます。

{
  "httpMethod": "DELETE",
  "headers": {
    "Accept": "*/*",
    "CloudFront-Forwarded-Proto": "https",
    "CloudFront-Is-Desktop-Viewer": "true",
    "CloudFront-Is-Mobile-Viewer": "false",
    "CloudFront-Is-SmartTV-Viewer": "false",
    "CloudFront-Is-Tablet-Viewer": "false",
    "CloudFront-Viewer-Country": "JP",
    "x-api-key": "XXXXXX",
  },

問題点

x-api-keyに表記揺れが発生するケースがあります。

X-API-KEY=XXXだとheaders.X-API-KEY: XXX
X-API-key=XXXだとheaders.X-API-key: XXX

対応

とりあえずheadersのキーに対してArray.findをかけて、比較する際に大文字 or 小文字に寄せることに。

import { APIGatewayProxyEvent } from 'aws-lambda'

const getAPIKey = (event: APIGatewayProxyEvent): string => {
  const key = Object.keys(event.headers).find(header => {
    return header.toLocaleLowerCase() === "x-api-key" 
  })
  return event.headers[key] || ''
}
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?