Logo

dev-resources.site

for different kinds of informations.

A Beginners Guide to Serverless API Gateway Authentication with Lambda Authorizer

Published at
12/21/2024
Categories
apigatewayauthentication
beginnersguidetoserverless
terraform
awslambda
Author
valaug
Author
6 person written this
valaug
open
A Beginners Guide to Serverless API Gateway Authentication with Lambda Authorizer

Understanding how to authenticate users via an API Gateway can be a challenging yet essential skill for developers, especially when dealing with third-party identity providers (IdPs) like Okta or Active Directory. This guide provides a clear, step-by-step explanation of the authentication flow using a Lambda Authorizer, making it easy for beginners to grasp.

The Authentication Flow

User Authentication:

The process begins when users enter their user ID and password into a login form. They send these credentials to a third-party IdP, such as Okta or Active Directory.
If the credentials are valid, the IdP authenticates the user and returns a token (often a JSON Web Token, or JWT). This token serves as proof that the user has been successfully authenticated.

API Call with Token:

Next, the user wants to access a resource via the API Gateway. To do this, they include the received token in the header of their API request.
This token is essential because it tells the API Gateway that the user is who they claim to be. Without this token, the request will be denied.

Lambda Authorizer for Validation:

Since you are not using AWS Cognito and are instead relying on a third-party IdP, a Lambda Authorizer comes into play. This is a custom piece of code that you write to validate the token.
When the API Gateway receives the request, it invokes the Lambda Authorizer. The authorizer extracts the token from the request header and checks its validity by communicating with the third-party IdP.

Authorization with IAM Policies:

Once the token is validated, the Lambda Authorizer also determines what actions the user is allowed to perform. This is done by specifying IAM policies within the authorizer.
These IAM policies dictate what AWS resources the user can access and what actions they can perform. For example, a user might have permission to read data from a database but not to write to it. The API Gateway then checks these policies against AWS IAM to ensure compliance.

Backend Invocation:

If the IAM policy allows the requested action, the API Gateway proceeds to invoke the intended backend service, which could be another Lambda function, an AWS service, or any other resource.
At this stage, the user’s request is processed, and they receive the desired response.

Special Note

It’s important to remember that the Lambda Authorizer does not need to validate the token for every single API call. To enhance performance and reduce latency, you can implement caching for the authorizer’s responses. This means that once a token is validated, subsequent requests with the same token can be processed faster.

Understanding this authentication flow is vital for anyone working with serverless architectures. Take the time to familiarize yourself with each step, practice explaining the process, and consider building a small project that implements these concepts. This knowledge will not only help you in interviews but will also empower you in real-world applications.

Terraform Template

To help you implement this flow, here’s a basic previous Terraform template that sets up an API Gateway with a Lambda Authorizer:

  resource "aws_api_gateway_rest_api" "api" {
    name        = "MyAPI"
    description = "API Gateway with Lambda Authorizer"
  }
  resource "aws_api_gateway_resource" "resource" {
    rest_api_id = aws_api_gateway_rest_api.api.id parent_id = aws_api_gateway_rest_api.api.root_resource_id
    path_part   = "example"
  }
  resource "aws_api_gateway_method" "method" {
    rest_api_id   = aws_api_gateway_rest_api.api.id resource_id = aws_api_gateway_resource.resource.id http_method = "GET" authorization = "CUSTOM"
    authorizer_id = aws_api_gateway_authorizer.authorizer.id } resource "aws_api_gateway_authorizer" "authorizer" {
    rest_api_id = aws_api_gateway_rest_api.api.id name = "MyLambdaAuthorizer"
    authorizer_uri = "${aws_lambda_function.authorizer.invoke_arn}"
    type        = "REQUEST"
    identity_source = "method.request.header.Authorization"
  }
  output "api_endpoint" {
    value = "${aws_api_gateway_rest_api.api.invoke_url}/example"
  }
Enter fullscreen mode Exit fullscreen mode

Here you will find the GitHub repository containing the code and instructions.

GitHub Repository - Coming Soon!

Ready to streamline your AWS deployments?

Start using Terraform to manage your infrastructure as code. Experiment with the provided code and share your experiences in the comments. If you liked this article, follow me for more content on AWS and Terraform.

Your participation is valuable, and I would love to hear from you.

awslambda Article's
30 articles in total
Favicon
Build a Crypto Price Alert System with Telegram and AWS Lambda
Favicon
Leveraging Docker with AWS Lambda for Custom Runtimes and Large Deployments
Favicon
Docker for Serverless: Customizing Functions and Scaling Flexibly
Favicon
Inventory Management with AWS Lambda λ
Favicon
Lambda Power Tuning: Una comparativa entre arquitecturas x86_64 y arm64
Favicon
A Beginners Guide to Serverless API Gateway Authentication with Lambda Authorizer
Favicon
Serverless Functions: Unlocking the Power of AWS Lambda, Azure Functions, and More
Favicon
Mastering Serverless and Event-Driven Architectures with AWS: Innovations in Lambda, EventBridge, and Beyond
Favicon
Parse UserParameters sent from AWS CodePipeline to AWS Lambda in Go
Favicon
Leveraging Amazon Connect for Real-Time Incident Response Calls
Favicon
Lambda Code Execution Freeze/Thaw
Favicon
Efficiently Delete Inactive User Data Using TypeScript and AWS Lambda
Favicon
Unlocking Serverless: Build Your First Python AWS Lambda Function
Favicon
Lamba LLRT(Low Latency Runtime Javascript)
Favicon
Building Scalable Microservices with AWS Lambda and Serverless
Favicon
Serverless Architecture Best Practices
Favicon
Deep Dive on Writing and Reading Data to DynamoDB Table from Lambda Functions Using AWS Cloud Map Service Discovery
Favicon
AWS Lambda in Deno or Bun
Favicon
Lambda extension to cache SSM and Secrets Values for PHP Lambda on CDK
Favicon
Create a Fast Node.js Serverless Backend Using AWS Lambda and DynamoDB
Favicon
30-day Learning Challenge: Day 2— Learning AWS S3
Favicon
AWS Lambda Functions Failure Management
Favicon
Understanding Load Balancers: How They Work, Types, Algorithms, and Use Cases
Favicon
How to Deploy Dart Functions to AWS Lambda
Favicon
Using Custom Authorization - Request based for AWS Lambda
Favicon
How to generate a presigned url to upload images to S3
Favicon
Create an AppSync API using Terraform
Favicon
Creating a Cognito Trigger using CDK and TypeScript
Favicon
API Gateway REST API with Lambda Integration
Favicon
AWS Lambda Runtime debate

Featured ones: