I am currently playing around a bit with AWS AppSync and I am trying to use the Lambda authoriser feature to do some custom auth for the GraphQL API.
I have the Lambda function set up with the correct resource-based policy to allow AppSync to invoke the function and I have AppSync's Default authorization mode
set to invoke my Lambda.
This is my lambda code:
exports.handler = (event) => {
console.log(JSON.stringify(event));
const response = {
isAuthorized: true,
};
console.log(JSON.stringify(response));
return response;
};
Now I am facing the issue that the Lambda authoriser is always giving me the following error when I attempt to run a GraphQL quarry:
Error: Request failed with status code 401
After debugging this problem for two hours I can say the following things:
Default authorization mode
to API key
or Amazon cognito user pool
without changing anything else my Query executes successfully.{"isAuthorized":true}
which means no Authorization Token
would result in a 401
.So as far as I can tell everything is as it should but I am still getting the 401
no matter what I do and im getting pretty frustrated.
After some very frustrating debugging I finally figured out that the problem was the Lambda handler function. As it turns out a Node.js lambda handlers should be async.
So changing the lambda to the following code fixes the issue:
exports.handler = async (event) => {
console.log(JSON.stringify(event));
const response = {
isAuthorized: true,
};
console.log(JSON.stringify(response));
return response;
};
I didn't know this, since until no I only used Python for Lambdas, and the problem was hard to spot since the console.log
's where still running correctly so I though the function was returning the correct data where as in fact it was returning null
.