Repository navigation
Description
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: ... # OptionalShould 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
brysontyrrell commentedon Jul 16, 2018
I would recommend sticking with established defaults.
Nullor unassigned should be 5 minutes. Template write should explicitly state0if they want auth on every invocation.brysontyrrell commentedon Jul 16, 2018
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.brettstack commentedon Jul 16, 2018
Updated. 5 minutes is the default (including if you specify null).
brettstack commentedon Jul 16, 2018
Specifying Authorizer on an Event is documented in the first code section:
Specifying
DefaultAuthorizeron theServerless::APIresource will implicitly set that Authorizer for all paths unless you override on the Event.brysontyrrell commentedon Jul 16, 2018
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?
brettstack commentedon Jul 16, 2018
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.
hoegertn commentedon Jul 17, 2018
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?
brettstack commentedon Jul 17, 2018
@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.
jakul commentedon Jul 31, 2018
@brettstack The current Swagger format does support referencing external authorizers, using the
authorizerUriproperty ofx-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.
brettstack commentedon Jul 31, 2018
@jakul to clarify, when I said
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.
brysontyrrell commentedon Jul 31, 2018
@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.
jkahn117 commentedon Jul 31, 2018
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
NONEauthorizer 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.brettstack commentedon Jul 31, 2018
@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).
brettstack commentedon Jul 31, 2018
@jkahn117 I previously stated you could use
nullto override for this scenario:However,
"NONE","OPEN","PUBLIC"or similar would be more explicit.1 remaining item
brysontyrrell commentedon Aug 1, 2018
Would the Lambda-level assignment only serve as an override or could we use that instead of the Global assignment in some cases?
brettstack commentedon Aug 1, 2018
@brysontyrrell That's correct. This will function the same as all other
Globals. You don't need to useGlobals.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
Eventwhere you want auth)jfuss commentedon Aug 1, 2018
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:
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
Refthe Auth, which then becomes clear where the resource is. This also follows closer to CloudFormation formats. When you just haveIt quickly becomes unclear what
MyCognitoAuthis. 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 onAWS::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 theServerless::Apiand then attach it to aServerless::Function? We started following the pattern of pushing Api Related config into theServerless::Api. This makes maintaining the code for the translator easier. We ran into a bunch of, add this property to bothFunctionandApiresources. The implicit Api (ones defined through the Events property with Type Api) is transformed to anAWS::Serverless::Apibefore the main transformation is done to CloudFormation. This is how Implicit Apis support BinaryMediaTypes. Have we thought of a way to push this into theApiinstead of theFunctionto keep things consistent?brettstack commentedon Aug 1, 2018
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
DefaultAuthorizerwhich gets applied to all paths/methods.The thing with
!Refon 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 MyAuthorizeror!GetAtt MyAuthorizer.Arnthroughout 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 aResourceyet you can't access it in the same way you reference other resources.TLDR: While
Authorizer: MyCognitoAuthseems strange/confusing, I think it would be more confusing if customers try to use!Ref MyAuthorizeror!GetAtt MyAuthorizer.Arnand get unexpected results.brettstack commentedon Aug 1, 2018
@johnbest my understanding is that you can use multiple Cognito User Pools, though I have not tried it https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-authorizer.html#cfn-apigateway-authorizer-providerarns
johnbest commentedon Aug 2, 2018
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
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
brettstack commentedon Aug 2, 2018
@johnbest I have confirmed with the API Gateway team that this is supported. It appears the console does not allow this, however.
brettstack commentedon Aug 8, 2018
Final syntax:
brettstack commentedon Aug 9, 2018
Initial PR #546
red8888 commentedon Sep 11, 2018
Does this support AuthorizationType: AWS_IAM
brettstack commentedon Sep 11, 2018
No it doesn't, though that is simple in comparison it's anyone wants to submit an RFC and PR
jairtrejo commentedon Sep 12, 2018
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:
And have that auto-hooked to the implicit API.
spencerbeggs commentedon Dec 3, 2018
@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:
I am using the proxy integration, does that matter?
brettstack commentedon Jan 23, 2019
IAM RFC #781 for those interested