Skip to content

How To Use It with Serverless

Chris/0 edited this page Jan 24, 2019 · 3 revisions

This authorizer is somewhat configurable, and the nature of API Gateway means that the configuration happens at the use site – that is, in the template defining the service using the authorizer.

  • Platform Authorizer must be configured as the 'TOKEN' flavor of authorizer. (This is the default.)
    • The identity validation expression (identityValidationExpression) should be /^Bearer +[-0-9a-zA-Z\._]*$/. This allows a request with a malformed Authorization header to be failed without invoking even the authorizer.
  • A 401 UNAUTHORIZED Gateway Response is recommended, so that response authorization headers can be set correctly.
    • Don't forget response CORS headers, as well.

None of these requirements are particularly complicated, and can be configured directly in your Serverless templates.

Here is an excerpt from an example Serverless template:


custom:
  <<: &authorizer # This can be repetitive if you have many functions, so use the YAML "anchor" feature.
    arn: arn:aws:lambda:eu-west-1:123456789012:function:Platform-Authorization-public-Authorizer
    identityValidationExpression: ^Bearer +[-0-9a-zA-Z\._]*$

functions:
  routeRequest:
    handler: handler.routeRequest
    events:
      - http:
          path: routeRequest
          method: POST
          authorizer: *authorizer

resources:
  Resources:
    AuthFailureGatewayResponse:
      Type: AWS::ApiGateway::GatewayResponse
      Properties:
        StatusCode: '401'
        ResponseType: UNAUTHORIZED
        ResponseTemplates:
          application/json: >
            {"message":$context.error.messageString}
        ResponseParameters:
          gatewayresponse.header.WWW-Authenticate: >-
            'Bearer realm="https://api.cimpress.io/", authorization_uri="https://cimpress.auth0.com/oauth/token"'
          gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
          gatewayresponse.header.Access-Control-Expose-Headers: "'WWW-Authenticate'"
        RestApiId:
          Ref: 'ApiGatewayRestApi'

For a service using HTTP integration, the context variable authorizer.principalId should be mapped to a custom header so that it can be read by the service. For a service using Lambda Proxy integration, the authorizer.principalId is available on the request context to be read directly.

Clone this wiki locally