localhostaws-sam-cliaws-sam

SAM Local doesn't appear to be running Authorizer functions


I've just gotten started using SAM Local, but am coming up againast an issue when trying to configure an Authorizer function for my endpoints.

I've been looking at the main SAM documentation for how to set up the Auth functions, but whenever I try to run the API locally with sam local start-api, it runs fine, but as if it's not even trying to run the auth functions.

I've tried defining the Auth in both the Global.API as well as defining an API resource in the Resources section of SAM's template.yaml

# template.yaml
Globals:
  Function:
    Timeout: 3
    CodeUri: src/
    Runtime: nodejs8.10
  Api:
    Auth:                        # Option #1: Defining it globally
      DefaultAuthorizer: CustomJWTAuthorizer
      Authorizers:
        CustomJWTAuthorizer:
          FunctionArn: !GetAtt AuthFunction.Arn    
Resources:
  UserApi:
    Auth:                        # Option #2: Defining it as an API resource
      Authorizers:
        MyLambdaTokenAuth:
          FunctionPayloadType: TOKEN
          FunctionArn: !GetAtt AuthFunction.Arn
      DefaultAuthorizer: MyLambdaTokenAuth
  GetUserFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: handler.getUser
      Events:
        GetUser:
          Type: Api
          Properties:
            Path: /users/{userId}
            Method: get
            Auth:                    # Option #3: Define it on the function level
              Authorizer: AuthFunction
            RestApiId:
                Ref: UserApi
  AuthFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: handler.authorize

I've tried printing out the event to the console, and can see that event.requestContext is just being populated with dummy data rather than being passed it if it were pushed live:

  // console.log(event)

  ...  
  resource: '/users/{userId}', 
  requestContext:     { resourceId: '123456',
     apiId: '1234567890',
     resourcePath: '/users/{userId}',
     httpMethod: 'GET',
     requestId: 'c6af9ac6-7b61-11e6-9a41-93e8deadbeef',
     accountId: '123456789012',
     stage: null,
     identity: 
      { apiKey: null,
        userArn: null,
        cognitoAuthenticationType: null,
        caller: null,
        userAgent: 'Custom User Agent String',
        user: null,
        cognitoIdentityPoolId: null,
        cognitoAuthenticationProvider: null,
        sourceIp: '127.0.0.1',
        accountId: null },
   extendedRequestId: null,
   path: '/users/{userId}' },
   ...

Solution

  • Edit: SAM Local nowadays supports Authorizers. As this is the accepted answer I unfortunately can't delete it. For details please check and upvote the answer below.

    Unfortunately the AWS SAM CLI doesn't support authorizers yet when running code locally. However there is an open feature request to add support for it: https://github.com/awslabs/aws-sam-cli/issues/137.