Mercury
Mercury

Reputation: 732

AWS AppSync Lambda authoriser always results in "Error: Request failed with status code 401"

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:

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.

Upvotes: 1

Views: 1727

Answers (2)

theGentleGiant
theGentleGiant

Reputation: 11

Whenever you receive an Error: Request failed with status code 401 in your AWS AppSync Console and you were using Lambda Authorizer as your custom Authorizer for your API. Irrespective of what are the frameworks you used to create the Infrastructure i.e., CDK or SAM or Serverless Framework. Check whether you have added these correctly for your Lanbda Authorizer

  • Check you have added proper policystatement to your Lambda Authorizer
  • Check you have added permission for your Lambda Authorizer to your API Eg: If you are using AWS CDK to create all your AppSync and Lambda Authorizer, Add these two things to solve the above error

    lambdaAuth.addToRolePolicy("your policy statement"),
    lambdaAuth.addPermission("appsync",{
     principal:  new ServicePrincipal("appsync.amazonaws.com"),
     action: "lambda:InvokeFunction"
    })

Upvotes: 1

Mercury
Mercury

Reputation: 732

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.

Upvotes: 1

Related Questions