Logo

dev-resources.site

for different kinds of informations.

AWS sam #3: sam local + ApiGateway Lambda authorizer

Published at
10/23/2023
Categories
aws
sam
dynamodb
apigateway
Author
olcortesb
Categories
4 categories in total
aws
open
sam
open
dynamodb
open
apigateway
open
Author
9 person written this
olcortesb
open
AWS sam #3: sam local + ApiGateway Lambda authorizer

En post anteriores comentaba las posibilidades que ofrece AWS sam para probar localmente nuestras Apis Con Dynamo DB y Generando Logs Localmente.

En la última actualización de AWS sam 02-04-2023, se agregó una interesante funcionalidad,la posibilidad de probar localmente los Authorizer que se tengan configurados en los ApiGateway.

En el siguiente repositorio de GitHub https://github.com/olcortesb/sam-api-authorizer he dejado una demo completa de como probar los Authorizer localmente.

A continuación dejo algunos detalles adicionales

Actualizar la versión de AWS sam:

La versión a partir de la cual esta funcionalidad está disponible es la 1.80.0

Para verificar la versión que tenemos instalada y actualizar:

sam --version
# SAM CLI, version 1.76.0

# For mac
brew upgrade aws-sam-cli

sam --version
# SAM CLI, version 1.81.0

Enter fullscreen mode Exit fullscreen mode

Como actualizar AWS sam Para distintos sistemas operativos:

manage-sam-cli-versions

Código e infraestructura

Dentro del proyecto se encontrarán tres archivos que son los principales:

  • template.yaml -> Definición de la infraestructura (Api y lambdas)

  • authorizer.js -> La lambda que contiene el Custom authorizer

  • handler.js -> la lambda que esta detrás del Api Gateway y el Authorizer.

Definiendo el Authorizer dentro de la API

# File template.yaml
Resources:
  LoggerApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: dev
      Auth:
        DefaultAuthorizer: JWTCustomAuthorizer
        Authorizers: # Definitions of authorizer
          JWTCustomAuthorizer:
            FunctionPayloadType: TOKEN
            FunctionArn: !GetAtt JWTAuthFunction.Arn
Enter fullscreen mode Exit fullscreen mode

Definiendo la lambda que se ejecutara para validar el Authorizer tipo TOKEN

# File template.yaml
  JWTAuthFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: authorizer.lambdaHandler
      Runtime: nodejs18.x
      CodeUri: .
      Architectures:
        - x86_64

Enter fullscreen mode Exit fullscreen mode

Código de lambda basada en él template que provee aws: Link

⚠️ No usar en producción, remplazar por la validación del JWT correspondiente.

// File authorizer.js
const validate_token_and_user = async (token)=>{
    // Validate token Demo
    // Do not use in productive environment
    // valide your token here
    console.log("Log from lambda authorizer ...");
    console.log("The token: ",token);
    if (token.split(' ').pop() === 'e81a50b9'){
        return true;
    }
    return false;
}

Enter fullscreen mode Exit fullscreen mode

Levantar el proyecto en local

Descargar el proyecto del repositorio: https://github.com/olcortesb/sam-api-authorizer

Ahora levantamos las APIs

sam local start-api -p 3002 --log-file logfile.txt

Enter fullscreen mode Exit fullscreen mode

Llamamos al endpoint /logger

Probamos pasando el token errado …

curl -X GET \
  'http://127.0.0.1:3002/logger' \
  --header 'Accept: */*' \
  --header 'Authorization: Bearer e81a50b9ddd'
# Response:
# { 
# "message": "User is not authorized to access this resource"
# }

Enter fullscreen mode Exit fullscreen mode

Y pasando el token correcto

curl -X GET \
  'http://127.0.0.1:3002/logger' \
  --header 'Accept: */*' \
  --header 'Authorization: Bearer e81a50b9'

# Response
# "OK"

Enter fullscreen mode Exit fullscreen mode

Finalmente, utilizando la funcionalidad de generar un log localmente como si fuera AWS CloudWatch (Link), podemos ver los logs que hemos dejado dentro de la lambda Authorizer.

START RequestId: c0bd0c4a-0722-4b82-8c68-d56c0b26d128 Version: $LATEST
2023-04-24T13:05:22.621Z c0bd0c4a-0722-4b82-8c68-d56c0b26d128 INFO Method ARN: arn:aws:execute-api:us-east-1:123456789012:1234567890/dev/GET/logger
2023-04-24T13:05:22.627Z c0bd0c4a-0722-4b82-8c68-d56c0b26d128 INFO Token fron event: Bearer e81a50b9
2023-04-24T13:05:22.628Z c0bd0c4a-0722-4b82-8c68-d56c0b26d128 INFO Log from lambda authorizer ...
2023-04-24T13:05:22.628Z c0bd0c4a-0722-4b82-8c68-d56c0b26d128 INFO El token: Bearer e81a50b9
END RequestId: c0bd0c4a-0722-4b82-8c68-d56c0b26d128
REPORT RequestId: c0bd0c4a-0722-4b82-8c68-d56c0b26d128 Init Duration: 1.69 ms Duration: 1523.58 ms Billed Duration: 1524 ms Memory Size: 128 MB Max Memory Used: 128 MB

Enter fullscreen mode Exit fullscreen mode

¡Eso es todo por ahora, espero sea útil, gracias!

Saludos

Referencias

sam Article's
30 articles in total
Favicon
Running lambdas locally using Javascript/Node.js
Favicon
Cut Your AWS Lambda Logging Costs: Filter Logs with AWS SAM
Favicon
Building a "Real-Time" Data Integration Platform on AWS
Favicon
Using Amazon Cognito with the user-password flow
Favicon
SAM Registration and Maintenance Ensuring Your Business Stays Compliant
Favicon
Utilizing the System for Award Management SAM for Government Contracting Success
Favicon
Secure API Gateway with Amazon Cognito using SAM
Favicon
Resources and Properties for AWS SAM
Favicon
Adding Cognito Authentication to our Serverless Dash App
Favicon
Using YAML anchors and aliases in a SAM template
Favicon
First impressions of CloudFormation’s IaC generator and CDK migrate
Favicon
Building Scalable Serverless Applications with AWS SQS and Lambda using SAM
Favicon
How to add CI/CD to my SAM project
Favicon
How to create serverless applications with AWS SAM (Serverless Application Model)
Favicon
Introduction to AWS SAM (Serverless Application Model)
Favicon
Help! How do I set DeletionPolicy to Retain for production only?
Favicon
An efficient way to build your serverless microservices. Part 3. CI/CD with AWS SAM.
Favicon
Leveraging Infrastructure as Code (IaC) for AWS Lambda: A Comparative Analysis of AWS SAM, Terraform, and Serverless Framework
Favicon
AWS Lambda with Rust and SAM
Favicon
Deploying Lambdas with AWS SAM & GitHub Actions: Step by Step
Favicon
Speed up new serverless application development with customized SAM templates
Favicon
Streamline AWS Development with CI/CD, SAM, and GitHub Actions
Favicon
AWS sam #3: sam local + ApiGateway Lambda authorizer
Favicon
✨ Porting Lambda Functions to AWS SAM
Favicon
Store Thumbnails from Your Live Stream Using AWS SAM CLI to Set Up Lambda Function and API Gateway
Favicon
AWS sam #2: sam local + logs
Favicon
AWS sam #1: sam local + DynamoDB
Favicon
Event-driven file management using S3 Notifications and Step Functions
Favicon
Folding as a Service with AWS StepFunctions
Favicon
Elevating Your Serverless Development with AWS SAM

Featured ones: