AWS Lambda 함수 URL을 사용하여 API 액세스 단순화: 내장된 보안으로 GET, POST, PUT 및 DELETE 처리

WBOY
풀어 주다: 2024-08-11 12:51:31
원래의
716명이 탐색했습니다.

Simplifying API Access with AWS Lambda Function URLs: Handling GET, POST, PUT, and DELETE with Built-in Security

When building serverless applications on AWS, AWS Lambda is often the go-to solution for running code without provisioning or managing servers. Traditionally, AWS API Gateway has been used to expose Lambda functions as RESTful APIs. However, AWS introduced Lambda Function URLs, a simpler way to invoke Lambda functions via HTTPS without the overhead of configuring an API Gateway. In this post, we'll explore how to use Lambda Function URLs to handle different HTTP methods—GET, POST, PUT, and DELETE—while incorporating security authentication.

What are Lambda Function URLs?

Lambda Function URLs provide a dedicated HTTP(S) endpoint for your Lambda function. This feature is particularly useful for single-function microservices, lightweight APIs, or when you need to expose a Lambda function to the public with minimal setup.

Setting Up a Lambda Function URL

First, let's create a Lambda function and configure its URL. You can do this via the AWS Management Console, AWS CLI, or Infrastructure as Code (IaC) tools like AWS CloudFormation or Terraform.

  1. Create a Lambda Function:

    • Go to the AWS Lambda console.
    • Click on "Create function."
    • Choose the "Author from scratch" option.
    • Define your function name, runtime, and execution role.
    • Write your function code or upload a deployment package.
  2. Create a Function URL:

    • Under your function’s configuration, select the “Function URL” tab.
    • Click on “Create Function URL.”
    • Choose the authorization type (e.g., AWS_IAM for authenticated access or NONE for public access).
    • Click "Create Function URL."
  3. Secure Your Function URL:

    • You can use AWS IAM for authentication by selecting AWS_IAM as the authorization type.
    • Create IAM roles or policies to control which users or services can invoke the function via the URL.
    • Optionally, you can implement custom authorization logic within the function itself to further restrict access.

Handling Different HTTP Methods

Lambda functions triggered by Function URLs can handle multiple HTTP methods—GET, POST, PUT, and DELETE—within a single function. Here’s a simple example of how to implement this:

import json def lambda_handler(event, context): # Determine the HTTP method http_method = event['httpMethod'] if http_method == 'GET': return handle_get(event) elif http_method == 'POST': return handle_post(event) elif http_method == 'PUT': return handle_put(event) elif http_method == 'DELETE': return handle_delete(event) else: return { 'statusCode': 405, 'body': json.dumps({'message': 'Method Not Allowed'}) } def handle_get(event): # Handle GET request logic return { 'statusCode': 200, 'body': json.dumps({'message': 'GET request received'}) } def handle_post(event): # Handle POST request logic return { 'statusCode': 200, 'body': json.dumps({'message': 'POST request received'}) } def handle_put(event): # Handle PUT request logic return { 'statusCode': 200, 'body': json.dumps({'message': 'PUT request received'}) } def handle_delete(event): # Handle DELETE request logic return { 'statusCode': 200, 'body': json.dumps({'message': 'DELETE request received'}) }
로그인 후 복사

Example of Securing the Function URL with IAM Authentication

If you opted to use AWS_IAM for securing your function URL, clients will need to sign requests using AWS SigV4 (Signature Version 4). Here’s a brief overview of how to make authenticated requests:

  1. Create an IAM User/Rolewith appropriate permissions to invoke the Lambda function.
  2. Sign the Request: Use AWS SDKs, CLI, or tools like Postman (with AWS IAM authentication) to sign the HTTP requests.
  3. Invoke the Function URL: Ensure the signed request contains valid credentials; otherwise, the request will be denied.

For example, with the AWS CLI:

aws lambda invoke-url https://.lambda-url..on.aws/ \ --http-method POST \ --body '{ "key": "value" }' \ --region  \ --profile 
로그인 후 복사

Conclusion

AWS Lambda Function URLs offer a streamlined way to expose Lambda functions via HTTP without the need for an API Gateway. By handling different HTTP methods (GET, POST, PUT, DELETE) within the Lambda function and securing access with AWS IAM, you can build lightweight, secure APIs quickly. Whether you’re developing a simple microservice or a more complex application, Lambda Function URLs are a powerful addition to your AWS toolkit.

위 내용은 AWS Lambda 함수 URL을 사용하여 API 액세스 단순화: 내장된 보안으로 GET, POST, PUT 및 DELETE 처리의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!