Skip to content

Instantly share code, notes, and snippets.

@sansmoraxz
Last active January 3, 2024 08:13
Show Gist options
  • Save sansmoraxz/59310c94dc224d5c0783e3d3973d8df1 to your computer and use it in GitHub Desktop.
Save sansmoraxz/59310c94dc224d5c0783e3d3973d8df1 to your computer and use it in GitHub Desktop.
SAM template with partial auth and working CORS using API gateway
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
LambdaName:
Type: String
Description: "Required name for the Lambda function"
CognitoUserPoolName:
Type: String
Description: "Required name for the Cognito User Pool"
CognitoUserPoolClientName:
Type: String
Description: "Required name for the Cognito User Pool Client"
Resources:
# userpool
MyCognitoUserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: !Ref CognitoUserPoolName
Policies:
PasswordPolicy:
MinimumLength: 8
UsernameAttributes:
- email
Schema:
- AttributeDataType: String
Name: email
Required: false
# userpool client
MyCognitoUserPoolClient:
Type: AWS::Cognito::UserPoolClient
Properties:
UserPoolId: !Ref MyCognitoUserPool
ClientName: !Ref CognitoUserPoolClientName
GenerateSecret: false
MyApi:
Type: AWS::Serverless::Api
Properties:
Name: My API gateway
StageName: Prod
Cors:
AllowMethods: "'*'"
AllowHeaders: "'*'"
AllowOrigin: "'*'"
Auth:
DefaultAuthorizer: MyCognitoAuthorizer
AddDefaultAuthorizerToCorsPreflight: false
Authorizers:
MyCognitoAuthorizer:
UserPoolArn: !GetAtt MyCognitoUserPool.Arn
AuthType: COGNITO_USER_POOLS
Func:
Type: AWS::Serverless::Function
Metadata:
SkipBuild: true
Properties:
FunctionName: !Ref LambdaName
InlineCode: |
def lambda_handler(event, context):
print(event)
return {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Headers" : "*",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*"
},
"body": "Hello from Lambda!"
}
Handler: index.lambda_handler
Runtime: python3.10
MemorySize: 128
Timeout: 30
Events:
ProtectedApi: # this is protected by Cognito
Type: Api
Properties:
Path: /test
Method: GET
RestApiId: !Ref MyApi
UnprotectedApi: # you can hit this from your browser
Type: Api
Properties:
Path: /unsafe
Method: GET
RestApiId: !Ref MyApi
Auth:
Authorizer: NONE
OverrideApiAuth: true
Outputs:
ApiEndpoint:
Description: "API endpoint URL for Prod stage"
Value: !Sub "https://${MyApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/"
CognitoUserPoolId:
Description: "Cognito User Pool ID"
Value: !Ref MyCognitoUserPool
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment