skip to Main Content

I would like to invoke an AWS Lambda Function (using Python) without being authenticated, like so:

from boto3 import client 
from botocore import UNSIGNED
from botocore.client import Config
from json import dumps

def invoke(functionName, params):
    lambda_client = client('lambda', 
                    aws_access_key_id='', 
                    aws_secret_access_key='', 
                    config=Config(signature_version=UNSIGNED),
                    region_name="us-east-2")

    response = lambda_client.invoke(FunctionName=functionName,
                     Payload=bytes(dumps(params), encoding='utf8'))
    return response["Payload"].read()

The above code will run into a Missing Authentication Token error (403?), however. The Lambda function is set up with a resource-based policy statement and role that allows FunctionURLPublicAccess, but I’m guessing that I need something else to indicate that any unauthenticated user can invoke this function.

Another way of solving this would be to invoke the Function URL instead, but I’m not finding any documentation on how to do that in Python. Looking into either way would be super helpful, thank you!

2

Answers


  1. If your function is set to use FunctionURLPublicAccess, you should use regular python tools for HTTP requests, not boto3. So you have to modify your code to use, for example, requests or python’s own urllib.

    Login or Signup to reply.
  2. If you want to invoke an AWS Lambda function, you can use the requests library in Python to make HTTP requests directly to the Lambda function endpoint:
    (Replace "YOUR_LAMBDA_FUNCTION_URL" with the actual URL of your Lambda function. This URL can be obtained from the AWS Lambda console.)

    import requests
    from json import dumps
        
        def invoke_lambda_function(lambda_url, params):
            headers = {
                'Content-Type': 'application/json',
            }
        
            response = requests.post(lambda_url, headers=headers, data=dumps(params))
        
            if response.status_code == 200:
                return response.text
            else:
                # Handle errors appropriately
                print(f"Error: {response.status_code}n{response.text}")
                return None
        
    # Example usage
    lambda_url = "YOUR_LAMBDA_FUNCTION_URL"
    response = invoke_lambda_function(lambda_url, {"key": "value"})
        
    if response is not None:
        print(response)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search