This is a simple example for Custom Authorizer of AWS API Gateway.
- This image from apigateway-use-lambda-authorizer.html.
Please see a detail example about Custom authorizer of Serverless framework in here.
- Do basic authentication with
login API. login APIvalidates a credential that is hardcoded. And generate and return a JWT.- When
hello APIis called,authfunction will be called beforehellohandler. authfunction validates a JWT in a request and generate the allow or deny policy document.- If allowed,
hellohandler is invoked and it responses proper value, that is, an event object in this example.
Please see details in handler.ts.
- Set your AWS profile and give it to proper permissions to deploy this stack.
sls deploycurl -XPOST "https://test:[email protected]/dev/login"and get a token from the response.curl -XGET -H "Authorization: Bearer TOKEN-FROM-RESPONSE" "https://API-ID.execute-id.REGION.amazonaws.com/dev/hello".
$ sls deploy ... endpoints: POST - https://API-ID.execute-api.REGION.amazonaws.com/dev/login GET - https://API-ID.execute-api.REGION.amazonaws.com/dev/hello1 GET - https://API-ID.execute-api.REGION.amazonaws.com/dev/hello2 GET - https://API-ID.execute-api.REGION.amazonaws.com/dev/hello3 functions: login: hello-custom-authorizer-dev-login auth: hello-custom-authorizer-dev-auth hello1: hello-custom-authorizer-dev-hello1 hello2: hello-custom-authorizer-dev-hello2 hello3: hello-custom-authorizer-dev-hello3 ... $ curl -XPOST "https://test:[email protected]/dev/login" {"token":"TOKEN-FROM-RESPONSE"} $ curl -XGET -H "Authorization: Bearer TOKEN-FROM-RESPONSE" "https://API-ID.execute-id.REGION.amazonaws.com/dev/hello1" {"hello":"1",{"resource":"/hello","path":"/hello","httpMethod":"GET","headers":{"Accept":"*/*","Authorization":"Bearer TOKEN-FROM-RESPONSE",...},...}} $ curl -v -XGET "https://API-ID.execute-id.REGION.amazonaws.com/dev/hello1" ... < HTTP/2 401 < content-type: application/json < content-length: 26 ... {"message":"Unauthorized"}
It has three hello API to see a cached policy can accept multiple functions by the methodArn with * scope. So we can see these functions are executed without auth function call because a policy was cached when called it first time.
$ curl -XGET -H "Authorization: Bearer TOKEN-FROM-RESPONSE" "https://API-ID.execute-id.REGION.amazonaws.com/dev/hello2" {"hello":"2",{"resource":"/hello","path":"/hello","httpMethod":"GET","headers":{"Accept":"*/*","Authorization":"Bearer TOKEN-FROM-RESPONSE",...},...}} $ curl -XGET -H "Authorization: Bearer TOKEN-FROM-RESPONSE" "https://API-ID.execute-id.REGION.amazonaws.com/dev/hello3" {"hello":"3",{"resource":"/hello","path":"/hello","httpMethod":"GET","headers":{"Accept":"*/*","Authorization":"Bearer TOKEN-FROM-RESPONSE",...},...}}