This plugin will protect routes using x-api-key similar to Api Gateway implementation. This is implemented through:
- Adding extra conditions in the Alb Http Listener
- New Rule to capture invalid key which will by default return status code 403 and json response with message
Forbidden
This plugins only support provider from aws
$ yarn add --dev serverless-plugin-albkey
Register this plugin in the serverless.yml For example:
service:
name: some-service
plugins:
- ....
- serverless-plugin-alb-apikey
- ...
Sample alb event without api key
albPingAuth:
handler: ${self:custom.path.app}/handlers/ping.handler
description: Ping Auth test from ALB
timeout: 5
reservedConcurrency: 1
events:
- alb:
listenerArn:
Ref: HTTPListener
priority: 3
conditions:
path: ['/ping/auth']
method: ['GET', 'POST']
Alb event setup with api key
albPingAuth:
handler: ${self:custom.path.app}/handlers/ping.handler
description: Ping Auth test from ALB
timeout: 5
reservedConcurrency: 1
events:
- alb:
listenerArn:
Ref: HTTPListener
priority: 3
apiKey: # api-key to check against - required - max 5 keys allowed
- ${env:AWS_ALB_API_KEY} # from env, custom, or provider
- 'xxxxyyyy' # or simple string value
conditions:
path: ['/ping/auth']
method: ['GET', 'POST']
actions: // optional, if you need to override the default actions
- Type: 'fixed-response'
FixedResponseConfig:
StatusCode: 403
ContentType: 'application/json'
MessageBody: '{ "custom error": "custom Forbidden message" }'
default error response
actions:
- Type: 'fixed-response'
FixedResponseConfig:
StatusCode: 403
ContentType: 'application/json'
MessageBody: '{ "message": "Forbidden: invalid api key" }'
This plugins is used as example in here - https://github.com/reflex-media/lesgo-lite
For each alb event
Extra condition is created to check for x-api-key header in the listener rule
Extra rule is also created to response forbidden access accordingly.