Skip to content

RFC: Authorizers #512

Closed
Closed

Description

@brettstack

Resources:
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html#cfn-apigateway-method-authorizationtype

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-authorizer.html

RFC Closure date: August 03 2018

API Gateway Authorizers come in three flavors - Cognito, Request Lambda, and Token Lambda. Both flavors of Lambda are very similar (TOKEN allows using a single header; REQUEST allows using multiple query strings, headers, stage variables, and "context"; these are sent as IdentitySource which also forms the cache key). We should be able to infer the Authorizer type based on the properties of the Authorizer, and allow the user to specify the Type when necessary.

Authorizers are unique compared to other things we've supported so far in SAM since they can be applied to multiple paths/methods of an API. As modelled in API Gateway, Authorizers are a child resource of an API, however, we don't need to model it that way in SAM. That is, Authorizers can either be defined as a property of a Serverless::API or established as an entirely new SAM Resource which can be used across multiple APIs.

The main benefit of defining Authorizers directly on the Serverless::API Resource is it is simpler/more concise. It also maps cleanly to API Gateway modeling which helps ensure future-proofing.

Globals:
  Api:
    Auth: # We will also define other auth options here such as Usage Plans/Api Keys, AWS_IAM, and Resource Policies
      Authorizers: # APIs can define multiple Authorizers
        MyAuth: # Authorizer properties will be discuused separately
          ... # Will go into detail on properties in a separate section
      DefaultAuthorizer: MyAuth # Optional; This will be used as the default Authorizer for all Resources/Methods; Alternate name: MainAuthorizer?
Resources:
  ServerlessRestApi: # This is the implicit API resource created when you don't specify an `ApiId` in an Api Event.
    Type: "AWS::Serverless::API"
    Properties:
      Auth:
        Authorizers:
          MyLambdaAuth:
            ...
          MyCognitoAuth:
            ...
        DefaultAuthorizer: MyLambdaAuth # NOTE: We are using the Authorizer name directly here (instead of !Ref/!GetAtt) since these are created in Swagger, not as CloudFormation resources.
  MyFn:
    Type: AWS::Serverless::Function
    Properties:
      ...
      Events:
        GetRoot:
          Type: Api
          Properties:
            Method: get
            Path: /
            Auth:
              Authorizer: MyCognitoAuth # Overrides the API's DefaultAuthorizer; can also specify null to make it open (null is default when no DefaultAuthorizer is specified)

The benefit of creating a new Serverless::Authorizer resource is it allows sharing Authorizers across multiple APIs*, and allows defining Authorizers for the Implicit API without needing to define the implicit ServerlessRestApi resource (which isn't obvious to users). The disadantages are it's less concise, and would increase the confusion around not referencing with !Ref/!GetAtt (the standar way you reference all other Resources).

  • You can achieve sharing of Authorizers with the other approach by defining them in Globals. However, this only works when the Authorizers are the same across the APIs which you want to share Authorizers; i.e. if you need to define an additional Authorizer, it will override all Authorizers defined in Globals.
Globals:
  Api:
    DefaultAuthorizer: MyCognitoAuth
  ApiAuthorizer:
    IdentityValidationExpression: abc_.*
Resources:
  MyCognitoAuth:
    Type: "AWS::Serverless::ApiAuthorizer" # NOTE: Authorizers will be generated as part of the Swagger document, not an AWS::ApiGateway::Authorizer CFN resource which you might expect when seeing this defined as a Resource like this.
    Properties:
      ...
  MyApi:
    Type: "AWS::Serverless::API"
    Properties:
      Auth:
        DefaultAuthorizer: MyCognitoAuth # Again, we are referencing direclty by name without using !Ref, which is what you would expect when referencing a Resource.

I am inclined for the former syntax defining Authorizers directly on an Api. The syntax is cleaner; maps to API Gateway modeling; and the lack of !Ref/!GetAtt will be less confusing. Exposing the Implicit API Resource is not desirable, but for most advanced use-cases users will define their own Api, making this a non-issue. I don't have any data on how useful "Shareable API Authorizers" is, but hopefully using Globals will be acceptable for most.

I'll use my preferred syntax for describing an Authorizers properties, but they should remain the same for whichever syntax we agree on.

Resources:
  MyApi:
    Type: AWS::Serverless::API
    Properties:
      Auth:
        Authorizers:
          MyCognitoAuth:
            Properties:
              Type: COGNITO_USER_POOLS # Optional; inferred due to existence of `UserPools`
              Name: ... # Optional; default to MyCognitoAuth (since Authorizer names don't need to be unique across APIs) or MyApiMyCognitoAuth (prefix with API name for consistency; likely be an issue when specifying Global Authorizers)
              UserPool: !GetAtt MyUserPool.Arn # Must specify either UserPool or UserPools
              UserPools: # Most of the time users will want to integrate with just a single UserPool; should we have 2 separate properties? Or a single `UserPools` which accepts both string and Array<string>?
                - !GetAtt MyUserPool.Arn
              RequestHeader: Authorization # is "Authorization" a sane default header? Sets IdentitySource to method.request.header.Authorization
              RequestHeaderValidationExpression: ... # Optional; ensures the request header matches a pattern before checking in with the Authorizer endpoint; is there a default we can set for Cognito User Pools Auth?

          MyLambdaTokenAuth:
            Properties:
              Type: LAMBDA_TOKEN # Optional; inferred due to existence of `RequestHeader`
              FunctionArn: !GetAtt MyAuthFn.Arn # Potential future enhancement might be to specify `Function` directly on the Authorizer
              RequestHeader: Authorization
              InvokeWithCredentials: ... # Optional; null (default) | arn:aws:iam::123456789012:role/S3Access | S3Access; NOTE: CALLER_CREDENTIALS is not a valid value here unlike the proposed InvokeWithCredentials on an Integration
              ReauthorizeEverySeconds: ... # Optional; Default: 300 (5 minutes); 0 means the authorizer will be called on every request
              RequestHeaderValidationExpression: ... # Optional

          MyLambdaRequesAuth:
            Properties:
              Type: LAMBDA_REQUEST # Optional; inferred due to existence of `RequestHeaders`, `RequestQueryStrings`, `RequestStageVariables`, or `RequestContext`
              FunctionArn: !GetAtt MyAuthFn.Arn
              RequestHeaders:
                - Authorization1 # method.request.header.Authorization1
              RequestQueryStrings:
                - Authorization2 # method.request.querystring.Authorization2
              RequestStageVariables: # "Request" doesn't make much sense for StageVariables or Context; I use it for consistency's sake
                - Authorization3 # stageVariables.Authorization3
              RequestContext:
                - Authorization4 #context.Authorization4
              # end result would be `IdentitySource: method.request.header.Authorization1,method.request.querystring.Authorization2,stageVariables.Authorization3,stageVariables.Authorization3`
              InvokeWithCredentials: ... # Optional
              ReauthorizeEverySeconds: ... # Optional
              RequestHeaderValidationExpression: ... # Optional

Should we stick with IdentitySource* as it exists in CloudFormation instead of renaming it to Request*? I think the latter is easier to understand in most cases, e.g. IdentitySourceHeader vs RequestHeader. Happy to hear alternatives.

Activity

  1. brysontyrrell commented on Jul 16, 2018

    @brysontyrrell
    Contributor

    ReauthorizeEverySeconds: ... # Optional; 0/null means the authorizer will be called on every request; should we default to 5 minutes like APIGW console?

    I would recommend sticking with established defaults. Null or unassigned should be 5 minutes. Template write should explicitly state 0 if they want auth on every invocation.

  2. brysontyrrell commented on Jul 16, 2018

    @brysontyrrell
    Contributor

    In your last example, where you detail your preferred syntax, you don't expand on how the authorizers would be assigned to endpoints. Is it assumed that the authorizer would be assigned to ALL endpoints?

    This is where I favor being able to assign the authorizer on the API Lambda as a part of the Event. This also would allow the same authorizer to be shared across multiple API Gateways as you mentioned. I'd also want the option of passing the ARN to the Authorizer Lambda as a template parameter for when I'm sharing a deployed authorizer across multiple services that are deployed in different templates.

  3. brettstack commented on Jul 16, 2018

    @brettstack
    ContributorAuthor

    Updated. 5 minutes is the default (including if you specify null).

  4. brettstack commented on Jul 16, 2018

    @brettstack
    ContributorAuthor

    Specifying Authorizer on an Event is documented in the first code section:

    MyFn:
        Type: AWS::Serverless::Function
        Properties:
          ...
          Events:
            GetRoot:
              Type: Api
              Properties:
                Method: get
                Path: /
                Auth:
                  Authorizer: MyCognitoAuth # Overrides the API's DefaultAuthorizer; can also specify null to make it open (null is default when no DefaultAuthorizer is specified)

    Specifying DefaultAuthorizer on the Serverless::API resource will implicitly set that Authorizer for all paths unless you override on the Event.

  5. brysontyrrell commented on Jul 16, 2018

    @brysontyrrell
    Contributor

    I'm following now. I like this, but the way the referencing is being done does that mean the authorizer must be in the same template as the API resources?

  6. brettstack commented on Jul 16, 2018

    @brettstack
    ContributorAuthor

    That's correct, the Authorizer needs to be created in the same template as the API because everything is created using Swagger which doesn't support referencing external Authorizers.

    EDIT: To clarify, you can re-use Lambda Functions/Authorizer Functions. I was referring to the API Gateway Authorizer itself (i.e. the Authorizer Configuration). See below comments for more details.

  7. hoegertn commented on Jul 17, 2018

    @hoegertn

    I really love the first approach with defining it on the API/Globals and referencing it in the Events part. Defining a pseudo resource does not look good to me, as it will confuse people because of it not being a real resource and not using !Ref.

    Is there a timeline for this feature?

  8. brettstack commented on Jul 17, 2018

    @brettstack
    ContributorAuthor

    @hoegertn I can't comment on timeline, but I have updated the RFC with a closure date of July 30. We'll begin implementation shortly after that, and you'll see progress via PR.

  9. jakul commented on Jul 31, 2018

    @jakul

    @brettstack The current Swagger format does support referencing external authorizers, using the authorizerUri property of x-amazon-apigateway-authorizer.

    I current have ~30 different APIs all using the same authorizer. I have one CF stack which creates/updates the authorizer lambda, and then one for each API.

  10. brettstack commented on Jul 31, 2018

    @brettstack
    ContributorAuthor

    @jakul to clarify, when I said

    the Authorizer needs to be created in the same template as the API because everything is created using Swagger which doesn't support referencing external Authorizers.

    I was talking about the API Gateway Authorizer itself. You are correct; you can point that Authorizer at any Lambda Function/Authorizer Function you want.

  11. brysontyrrell commented on Jul 31, 2018

    @brysontyrrell
    Contributor

    @brettstack That's the pattern I'd like to be able to follow while leveraging the new options. I may not have explained that very well the first time. I want to have my authorizer maintained on its own and used across numerous serverless apps.

  12. jkahn117 commented on Jul 31, 2018

    @jkahn117

    My preference is the first approach -- in my experience the Global approach with a function-level override will cover most use cases. That said, the implicit API resource is confusing, but would think this would be a secondary case.

    Agree with @brysontyrrell comment that the authorizer itself should be maintainable elsewhere, outside of the one template.

    Is a NONE authorizer type needed also? Use case would be an API that mixes public and private endpoints. I would want to private to be default and then override as opposed to needing to define auth config on each function.

  13. brettstack commented on Jul 31, 2018

    @brettstack
    ContributorAuthor

    @brysontyrrell that was my misunderstanding (damn ambiguity). You will be able to create Lambda Functions/Authorizer Functions in separate stacks and reference them across other stacks using !Import, Parameters, hardcoded ARN, etc.

    When I was talking about Authorizer reusability, I was talking about reusing the configuration of an Authorizer (i.e. the API Gateway Authorizer resource).

  14. brettstack commented on Jul 31, 2018

    @brettstack
    ContributorAuthor

    @jkahn117 I previously stated you could use null to override for this scenario:

    Authorizer: MyCognitoAuth # Overrides the API's DefaultAuthorizer; can also specify null to make it open (null is default when no DefaultAuthorizer is specified)
    

    However, "NONE", "OPEN", "PUBLIC" or similar would be more explicit.

  15. 1 remaining item

  16. brysontyrrell commented on Aug 1, 2018

    @brysontyrrell
    Contributor

    Would the Lambda-level assignment only serve as an override or could we use that instead of the Global assignment in some cases?

  17. brettstack commented on Aug 1, 2018

    @brettstack
    ContributorAuthor

    @brysontyrrell That's correct. This will function the same as all other Globals. You don't need to use Globals.

    Worth calling out you can also use Function-level Auth without specifying it on the API level. API level will apply an auth strategy as the default strategy for all endpoints, but if you only have 1 endpoint which requires auth you wouldn't want to specify it at that level (i.e. you would only specify it on the single Event where you want auth)

  18. jfuss commented on Aug 1, 2018

    @jfuss
    Contributor

    Sorry longer post and some things may already been covered. Just dumping my thoughts here.

    Generally, I think I agree with what is here. I find the schema difficult and cumbersome through. Example taken from above:

    Resources:
      MyApi:
        Type: AWS::Serverless::API
        Properties:
          Auth:
            Authorizers:
              MyCognitoAuth:
                Properties:
                  Type: COGNITO_USER_POOLS # Optional; inferred due to existence of `UserPools`
                  Name: ... # Optional; default to MyCognitoAuth (since Authorizer names don't need to be unique across APIs) or MyApiMyCognitoAuth (prefix with API name for consistency; likely be an issue when specifying Global Authorizers)
                  UserPool: !GetAtt MyUserPool.Arn # Must specify either UserPool or UserPools
                  UserPools: # Most of the time users will want to integrate with just a single UserPool; should we have 2 separate properties? Or a single `UserPools` which accepts both string and Array<string>?
                    - !GetAtt MyUserPool.Arn
                  RequestHeader: Authorization # is "Authorization" a sane default header? Sets IdentitySource to method.request.header.Authorization
                  RequestHeaderValidationExpression: ... # Optional; ensures the request header matches a pattern before checking in with the Authorizer endpoint; is there a default we can set for Cognito User Pools Auth?
    

    This is deeply nested and resembles a stand alone resource placed inside another. I find this makes templates harder to read and write. What is the motivation behind this?

    I am in favor of the separate resource for Auth. This yields better reusability and easier to reason about. This would allow customers to Ref the Auth, which then becomes clear where the resource is. This also follows closer to CloudFormation formats. When you just have

    Authorizer: MyCognitoAuth
    

    It quickly becomes unclear what MyCognitoAuth is. Is it a string? A LogicalId? A template represents resources and your infrastructure. Explicit is better in these cases (imo).

    Is this only supported through AWS::Serverless::Function? No property on AWS::Serverless::Api? I know there is a default you can set but wondering how we support customers that use the non-implicit definitions and want to update their Api through this property? Do they need to update the Serverless::Api and then attach it to a Serverless::Function? We started following the pattern of pushing Api Related config into the Serverless::Api. This makes maintaining the code for the translator easier. We ran into a bunch of, add this property to both Function and Api resources. The implicit Api (ones defined through the Events property with Type Api) is transformed to an AWS::Serverless::Api before the main transformation is done to CloudFormation. This is how Implicit Apis support BinaryMediaTypes. Have we thought of a way to push this into the Api instead of the Function to keep things consistent?

  19. brettstack commented on Aug 1, 2018

    @brettstack
    ContributorAuthor

    Is this only supported through AWS::Serverless::Function?

    What you are referring to is only supported on the Function because it is overriding a Resource/Path/Method. There is no concept of this at the API level, so we only expose a DefaultAuthorizer which gets applied to all paths/methods.

    The thing with !Ref on an Authorizer is it's not really a !Ref. That is, because these are constructed using Swagger and not CloudFormation resources, you can't use !Ref MyAuthorizer or !GetAtt MyAuthorizer.Arn throughout the rest of your template. This is an implementation detail that most SAM users don't need to understand, but it is also a technical limitation and may lead to more confusion if we were to define it as a Resource yet you can't access it in the same way you reference other resources.

    TLDR: While Authorizer: MyCognitoAuth seems strange/confusing, I think it would be more confusing if customers try to use !Ref MyAuthorizer or !GetAtt MyAuthorizer.Arn and get unexpected results.

  20. johnbest commented on Aug 2, 2018

    @johnbest

    I have tried setting multiple cognito pools using the AWS Console and it hasn't worked- There could be a trick to it I am missing.

    All of this page refers to a single user pool.

    https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html

    This page mostly refers to a single user pool, apart from the bit I have highlighted below. (Which is about configuring)
    https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-enable-cognito-user-pool.html

      "securityDefinitions": {
    
    "MyUserPool": {
    
      "type": "apiKey",
    
      "name": "Authorization",
    
      "in": "header",
    
      "x-amazon-apigateway-authtype": "cognito_user_pools",
    
      "x-amazon-apigateway-authorizer": {
    
        "type": "cognito_user_pools",
    
        "providerARNs": [
    
          "arn:aws:cognito-idp:{region}:{account_id}:userpool/{user_pool_id}"
    
        ]
    
      }
    }
    

    Could you get a confirmation on the multiple User Pools - it would be a real life saver.
    (although I would possibly need to start using swagger until this update is done I suppose.)

    Thanks very much

  21. brettstack commented on Aug 2, 2018

    @brettstack
    ContributorAuthor

    @johnbest I have confirmed with the API Gateway team that this is supported. It appears the console does not allow this, however.

  22. brettstack commented on Aug 8, 2018

    @brettstack
    ContributorAuthor

    Final syntax:

    Resources:
      # Minimum config for each type of authorizer being applied to an entire API:
      MyApiWithCognitoAuth:
          Type: "AWS::Serverless::Api"
          Properties:
            Auth:
              DefaultAuthorizer: MyCognitoAuth
              Authorizers:
                MyCognitoAuth:
                  UserPoolArn: !GetAtt MyUserPool.Arn
    
      MyApiWithLambdaTokenAuth:
          Type: "AWS::Serverless::Api"
          Properties:
            Auth:
              DefaultAuthorizer: MyLambdaTokenAuth
              Authorizers:
                MyLambdaTokenAuth:
                  FunctionArn: !GetAtt MyAuthFn.Arn
    
      MyApiWithLambdaRequestAuth:
          Type: "AWS::Serverless::Api"
          Properties:
            Auth:
              DefaultAuthorizer: MyLambdaRequestAuth
              Authorizers:
                MyLambdaRequestAuth:
                  FunctionPayloadType: REQUEST
                  FunctionArn: !GetAtt MyAuthFn.Arn
                  Identity:
                    Headers:
                      - Authorization1
      
      # All configuration options:
      MyApi:
        Type: "AWS::Serverless::Api"
        Properties:
          Auth: # We will eventually define other auth options here such as Usage Plans/Api Keys, AWS_IAM, and Resource Policies
            Authorizers:
              MyCognitoAuth:
                UserPoolArn: !GetAtt MyUserPool.Arn # Can be a string, or array<string>
                Identity: # Optional
                  Header: ... # Optional; Default: Authorization
                  ValidationExpression: ...  # Optional; ensures the request header matches a pattern before checking in with the Authorizer endpoint; is there a default we can set for Cognito User Pools Auth?
    
              MyLambdaTokenAuth:
                FunctionPayloadType: TOKEN # Optional; default: TOKEN
                FunctionArn: !GetAtt MyAuthFn.Arn
                FunctionInvokeRole: ... # Optional; Default: "NONE" | arn:aws:iam::123456789012:role/S3Access | S3Access; NOTE: CALLER_CREDENTIALS is not a valid value here unlike the proposed (see IAM RFC) FunctionInvokeRole on an Integration
                Identity: # Optional
                  Header: ... # Optional; Default: Authorization
                  ValidationExpression: ... # Optional
                  ReauthorizeEvery: ... # Optional; Default: 300 (5 minutes); 0 means the authorizer will be called on every request (i.e no caching)
    
              MyLambdaRequestAuth:
                FunctionPayloadType: REQUEST
                FunctionArn: !GetAtt MyAuthFn.Arn
                FunctionInvokeRole: ... # Optional
                Identity:
                  Headers:
                    - Authorization1 # method.request.header.Authorization1
                  QueryStrings:
                    - Authorization2 # method.request.querystring.Authorization2
                  StageVariables:
                    - Authorization3 # stageVariables.Authorization3
                  Context:
                    - Authorization4 #context.Authorization4
                  # end result would be `IdentitySource: method.request.header.Authorization1,method.request.querystring.Authorization2,stageVariables.Authorization3,stageVariables.Authorization3`
                  ReauthorizeEvery: ... # Optional
            DefaultAuthorizer: MyLambdaTokenAuth # Optional; This will be used as the default Authorizer for all Resources/Methods of this API
    
      # Setting/Overriding a Method/Path's Authorizer:
      MyFn:
        Type: AWS::Serverless::Function
        Properties:
          ...
          Events:
            GetRoot:
              Type: Api
              Properties:
                RestApiId: MyApi
                Method: get
                Path: /
                Auth:
                  Authorizer: MyCognitoAuth # Overrides the API's DefaultAuthorizer; can also specify "NONE" to make it open ("NONE" is default when no DefaultAuthorizer is specified on the Api)
    
    # Globals; out of scope for initial launch
    Globals:
      Api:
        Auth:
          Authorizers: # Allows a way to share Authorizer settings across APIs
            MyAuth:
              ...
          DefaultAuthorizer: MyAuth
  23. brettstack commented on Aug 9, 2018

    @brettstack
    ContributorAuthor

    Initial PR #546

  24. red8888 commented on Sep 11, 2018

    @red8888

    Does this support AuthorizationType: AWS_IAM

  25. brettstack commented on Sep 11, 2018

    @brettstack
    ContributorAuthor

    No it doesn't, though that is simple in comparison it's anyone wants to submit an RFC and PR

  26. jairtrejo commented on Sep 12, 2018

    @jairtrejo

    I'm way too late, but for the specific case of lambda authorizers, it would be sweet to be able to define an authorizer function like:

    MyAuthorizerFn:
      Type: AWS::Serverless::Function
      Properties:
        ...
        Events:
          Authorize:
            PayloadType: TOKEN
            Identity:
              Header: X-Authorization
              ReauthorizeEvery: 600

    And have that auto-hooked to the implicit API.

  27. spencerbeggs commented on Dec 3, 2018

    @spencerbeggs

    @brettstack Does setting a Validation Expression on a CongitoPool Authorizer enable us to check the claims inside the JWT? For example, let's say I have a Cognito Group called "admin: in my user pool that I want test against:

    Resources:
      API:
        Type: AWS::Serverless::Api
        Properties:
          StageName: Prod
          Cors: "'https://example.com'"
          Auth:
            DefaultAuthorizer: AdminAuthorizer
            Authorizers:
              AdminAuthorizer:
                UserPoolArn: !GetAtt UserPool.Arn
                Identity:
                  Header: "method.requestContext.authorizer.claims['cognito:groups']"
                  ValidationExpression: "(?!,)?(admin)(?!,)?"

    I am using the proxy integration, does that matter?

  28. brettstack commented on Jan 23, 2019

    @brettstack
    ContributorAuthor

    IAM RFC #781 for those interested

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions