Trouble with connecting http post method with AWS lambda authorizer to front-end of the application

111 Views Asked by At

I created a form to add slots in my web application. I created a lambda authorizer for my route in API gateway.

API route is functional in postman with lambda authorizer. However once I connect it to the front end I am getting errors which I am not sure how to solve.

Error in console

enter image description here CORS configuration

enter image description here

Javascript code to add slot and validate user's access token

function addSlots() {
        var response = "";
        var jsonData = new Object();
        jsonData.restaurant_name_date_time = document.getElementById("date_time_slot").value;
        jsonData.number_of_pax = document.getElementById("number_of_pax_2").value;
        jsonData.restaurant_name = document.getElementById("restaurant_name_slot").value;
        // validate the access token
        var access_token = document.getElementById("access_token").value;
       
        var request = new XMLHttpRequest();
        request.open("POST", "https://aba3bnzddd.execute-api.us-east-1.amazonaws.com/slots", true);
        request.setRequestHeader("Authorization", "Bearer " + access_token); 

      
        request.onload = function () {

            response = JSON.parse(request.responseText);
            console.log(response)
            if (response.message == "slot added") {
                alert('Congrats! You have succesfully added a slot');
            } else if (response.message == "forbidden") {
                alert('Invalid token. Please enter a valid access token.');
            } else {
                alert('Error. Unable to add slot.');
            }
        };
        request.send(JSON.stringify(jsonData));
}

Lambda Authorizer Code

import json

def lambda_handler(event, context):
    
    if event['headers']['authorization'] == 'secretcode':
        response = {
            "isAuthorized": True,
            "context": {
                "anyotherparam": "values"
            }
        }
        return response
        
    else: 
        response = {
            "isAuthorized": False,
            "context": {
                "anyotherparam": "values"
            }
        }
        return response
1

There are 1 best solutions below

4
obe On

Try to return the CORS headers using your own code that runs in the Lambda function. E.g. something like this:

let headers = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "POST, GET, OPTIONS, HEAD",
    "Access-Control-Allow-Headers": "*",
};

// Lambda function response to API Gateway...
return {
    statusCode: 200,
    headers: headers,
    body: ...
};