Lambda Authorizer not returning proper error message with callback() in node.js The Next CEO of Stack OverflowAWS API Gateway Custom Authorizer AuthorizerConfigurationExceptionAWS API Gateway with custom authorizer returns AuthorizerConfigurationExceptionHow to access http headers in custom authorizer AWS lambda functionAWS API Gateway Custom Authorizer AuthorizerConfigurationExceptionAWS API Gateway custom authorizer. How to access principalId in lambdaHow to throw custom error message from API Gateway custom authorizerAWS: Restrict Cognito Authorized User to specific Lambda FunctionsHandling errors and callbacks in API Gateway Lambda ProxyTransform upstream request query params using Lambda Authorizer outcomeCustom response Lambda Authorizer for 401How to customise “Unauthorized” error message from AWS Lambda authorizerX-Amzn-Trace-Id not present in response header when response status is other than 200
What does "Its cash flow is deeply negative" mean?
MessageLevel in QGIS3
multiple labels for a single equation
Why has the US not been more assertive in confronting Russia in recent years?
Is micro rebar a better way to reinforce concrete than rebar?
I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin
Is there an analogue of projective spaces for proper schemes?
Are there any limitations on attacking while grappling?
Indicator light circuit
How did people program for Consoles with multiple CPUs?
What is the purpose of the Evocation wizard's Potent Cantrip feature?
How to transpose the 1st and -1th levels of arbitrarily nested array?
What connection does MS Office have to Netscape Navigator?
Should I tutor a student who I know has cheated on their homework?
Why didn't Khan get resurrected in the Genesis Explosion?
Why do we use the plural of movies in this phrase "We went to the movies last night."?
If a black hole is created from light, can this black hole then move at speed of light?
What benefits would be gained by using human laborers instead of drones in deep sea mining?
Skipping indices in a product
How to avoid supervisors with prejudiced views?
Contours of a clandestine nature
Why does the UK parliament need a vote on the political declaration?
Is it professional to write unrelated content in an almost-empty email?
What can we do to stop prior company from asking us questions?
Lambda Authorizer not returning proper error message with callback() in node.js
The Next CEO of Stack OverflowAWS API Gateway Custom Authorizer AuthorizerConfigurationExceptionAWS API Gateway with custom authorizer returns AuthorizerConfigurationExceptionHow to access http headers in custom authorizer AWS lambda functionAWS API Gateway Custom Authorizer AuthorizerConfigurationExceptionAWS API Gateway custom authorizer. How to access principalId in lambdaHow to throw custom error message from API Gateway custom authorizerAWS: Restrict Cognito Authorized User to specific Lambda FunctionsHandling errors and callbacks in API Gateway Lambda ProxyTransform upstream request query params using Lambda Authorizer outcomeCustom response Lambda Authorizer for 401How to customise “Unauthorized” error message from AWS Lambda authorizerX-Amzn-Trace-Id not present in response header when response status is other than 200
I have created a Lambda Authorizer on a AWS API Gateway, which calls a Lambda Function. Following is the code in the Lambda Function written in Node.js 8.0 code.
exports.handler = function(event, context, callback)
var token = event.authorizationToken;
switch (token.toLowerCase())
case 'allow':
callback(null, generatePolicy('user', 'Allow', event.methodArn));
break;
case 'deny':
callback(null, generatePolicy('user', 'Deny', event.methodArn));
break;
case 'unauthorized':
callback("Unauthorized"); // Return a 401 Unauthorized response
break;
default:
callback("Error: Invalid token");
;
// Help function to generate an IAM policy
var generatePolicy = function(principalId, effect, resource)
var authResponse = ;
authResponse.principalId = principalId;
if (effect && resource)
var policyDocument = ;
policyDocument.Version = '2012-10-17';
policyDocument.Statement = [];
var statementOne = ;
statementOne.Action = 'execute-api:Invoke';
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
// Optional output with custom properties of the String, Number or Boolean type.
authResponse.context =
"stringKey": "stringval",
"numberKey": 123,
"booleanKey": true
;
return authResponse;
(The above sample code if from the web site https://markpollmann.com/lambda-authorizer/)
If I save and Test this function by passing an invalid value for authorizationToken, I get expected result which is below.
Response:
"errorMessage": "Error: Invalid token"
Request ID:
"e93567c0-fcbb-4cb1-b0b3-28e9c1b30162"
But If I call this API from Postman, by passing the value in the header, I get the following response. I am getting this error for any value in the header i.e, deny, allow, unauthorized, wrong etc.
"message": null
The status message in postman shows "500 Internal Server Error". Following is the detail from header section in postman.
content-length →16
content-type →application/json
date →Fri, 08 Mar 2019 14:07:57 GMT
status →500
x-amz-apigw-id →W89kFDRDoEFxYg=
x-amzn-errortype →AuthorizerConfigurationException
x-amzn-requestid →92f31d11-41ab-11e9-9c36-97d38d96f31b
I do not understand why the API is returning the above response and error message, while the Lambda test is working fine.
I have already gone through the following two threads in SO, but the answers/comments couldn't help in my case.
AWS API Gateway with custom authorizer returns AuthorizerConfigurationException
AWS API Gateway Custom Authorizer AuthorizerConfigurationException
node.js aws-lambda aws-api-gateway
add a comment |
I have created a Lambda Authorizer on a AWS API Gateway, which calls a Lambda Function. Following is the code in the Lambda Function written in Node.js 8.0 code.
exports.handler = function(event, context, callback)
var token = event.authorizationToken;
switch (token.toLowerCase())
case 'allow':
callback(null, generatePolicy('user', 'Allow', event.methodArn));
break;
case 'deny':
callback(null, generatePolicy('user', 'Deny', event.methodArn));
break;
case 'unauthorized':
callback("Unauthorized"); // Return a 401 Unauthorized response
break;
default:
callback("Error: Invalid token");
;
// Help function to generate an IAM policy
var generatePolicy = function(principalId, effect, resource)
var authResponse = ;
authResponse.principalId = principalId;
if (effect && resource)
var policyDocument = ;
policyDocument.Version = '2012-10-17';
policyDocument.Statement = [];
var statementOne = ;
statementOne.Action = 'execute-api:Invoke';
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
// Optional output with custom properties of the String, Number or Boolean type.
authResponse.context =
"stringKey": "stringval",
"numberKey": 123,
"booleanKey": true
;
return authResponse;
(The above sample code if from the web site https://markpollmann.com/lambda-authorizer/)
If I save and Test this function by passing an invalid value for authorizationToken, I get expected result which is below.
Response:
"errorMessage": "Error: Invalid token"
Request ID:
"e93567c0-fcbb-4cb1-b0b3-28e9c1b30162"
But If I call this API from Postman, by passing the value in the header, I get the following response. I am getting this error for any value in the header i.e, deny, allow, unauthorized, wrong etc.
"message": null
The status message in postman shows "500 Internal Server Error". Following is the detail from header section in postman.
content-length →16
content-type →application/json
date →Fri, 08 Mar 2019 14:07:57 GMT
status →500
x-amz-apigw-id →W89kFDRDoEFxYg=
x-amzn-errortype →AuthorizerConfigurationException
x-amzn-requestid →92f31d11-41ab-11e9-9c36-97d38d96f31b
I do not understand why the API is returning the above response and error message, while the Lambda test is working fine.
I have already gone through the following two threads in SO, but the answers/comments couldn't help in my case.
AWS API Gateway with custom authorizer returns AuthorizerConfigurationException
AWS API Gateway Custom Authorizer AuthorizerConfigurationException
node.js aws-lambda aws-api-gateway
add a comment |
I have created a Lambda Authorizer on a AWS API Gateway, which calls a Lambda Function. Following is the code in the Lambda Function written in Node.js 8.0 code.
exports.handler = function(event, context, callback)
var token = event.authorizationToken;
switch (token.toLowerCase())
case 'allow':
callback(null, generatePolicy('user', 'Allow', event.methodArn));
break;
case 'deny':
callback(null, generatePolicy('user', 'Deny', event.methodArn));
break;
case 'unauthorized':
callback("Unauthorized"); // Return a 401 Unauthorized response
break;
default:
callback("Error: Invalid token");
;
// Help function to generate an IAM policy
var generatePolicy = function(principalId, effect, resource)
var authResponse = ;
authResponse.principalId = principalId;
if (effect && resource)
var policyDocument = ;
policyDocument.Version = '2012-10-17';
policyDocument.Statement = [];
var statementOne = ;
statementOne.Action = 'execute-api:Invoke';
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
// Optional output with custom properties of the String, Number or Boolean type.
authResponse.context =
"stringKey": "stringval",
"numberKey": 123,
"booleanKey": true
;
return authResponse;
(The above sample code if from the web site https://markpollmann.com/lambda-authorizer/)
If I save and Test this function by passing an invalid value for authorizationToken, I get expected result which is below.
Response:
"errorMessage": "Error: Invalid token"
Request ID:
"e93567c0-fcbb-4cb1-b0b3-28e9c1b30162"
But If I call this API from Postman, by passing the value in the header, I get the following response. I am getting this error for any value in the header i.e, deny, allow, unauthorized, wrong etc.
"message": null
The status message in postman shows "500 Internal Server Error". Following is the detail from header section in postman.
content-length →16
content-type →application/json
date →Fri, 08 Mar 2019 14:07:57 GMT
status →500
x-amz-apigw-id →W89kFDRDoEFxYg=
x-amzn-errortype →AuthorizerConfigurationException
x-amzn-requestid →92f31d11-41ab-11e9-9c36-97d38d96f31b
I do not understand why the API is returning the above response and error message, while the Lambda test is working fine.
I have already gone through the following two threads in SO, but the answers/comments couldn't help in my case.
AWS API Gateway with custom authorizer returns AuthorizerConfigurationException
AWS API Gateway Custom Authorizer AuthorizerConfigurationException
node.js aws-lambda aws-api-gateway
I have created a Lambda Authorizer on a AWS API Gateway, which calls a Lambda Function. Following is the code in the Lambda Function written in Node.js 8.0 code.
exports.handler = function(event, context, callback)
var token = event.authorizationToken;
switch (token.toLowerCase())
case 'allow':
callback(null, generatePolicy('user', 'Allow', event.methodArn));
break;
case 'deny':
callback(null, generatePolicy('user', 'Deny', event.methodArn));
break;
case 'unauthorized':
callback("Unauthorized"); // Return a 401 Unauthorized response
break;
default:
callback("Error: Invalid token");
;
// Help function to generate an IAM policy
var generatePolicy = function(principalId, effect, resource)
var authResponse = ;
authResponse.principalId = principalId;
if (effect && resource)
var policyDocument = ;
policyDocument.Version = '2012-10-17';
policyDocument.Statement = [];
var statementOne = ;
statementOne.Action = 'execute-api:Invoke';
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
// Optional output with custom properties of the String, Number or Boolean type.
authResponse.context =
"stringKey": "stringval",
"numberKey": 123,
"booleanKey": true
;
return authResponse;
(The above sample code if from the web site https://markpollmann.com/lambda-authorizer/)
If I save and Test this function by passing an invalid value for authorizationToken, I get expected result which is below.
Response:
"errorMessage": "Error: Invalid token"
Request ID:
"e93567c0-fcbb-4cb1-b0b3-28e9c1b30162"
But If I call this API from Postman, by passing the value in the header, I get the following response. I am getting this error for any value in the header i.e, deny, allow, unauthorized, wrong etc.
"message": null
The status message in postman shows "500 Internal Server Error". Following is the detail from header section in postman.
content-length →16
content-type →application/json
date →Fri, 08 Mar 2019 14:07:57 GMT
status →500
x-amz-apigw-id →W89kFDRDoEFxYg=
x-amzn-errortype →AuthorizerConfigurationException
x-amzn-requestid →92f31d11-41ab-11e9-9c36-97d38d96f31b
I do not understand why the API is returning the above response and error message, while the Lambda test is working fine.
I have already gone through the following two threads in SO, but the answers/comments couldn't help in my case.
AWS API Gateway with custom authorizer returns AuthorizerConfigurationException
AWS API Gateway Custom Authorizer AuthorizerConfigurationException
node.js aws-lambda aws-api-gateway
node.js aws-lambda aws-api-gateway
edited Mar 8 at 14:42
KurioZ7
asked Mar 8 at 13:59
KurioZ7KurioZ7
2,64852341
2,64852341
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
You cannot simply access event.methodArn from your event object inside your Lambda function.
When you test it from the console, the exact JSON you are providing to your Lambda function is going to be injected in your event object, however, when the call is proxied through API Gateway, you will then need to access the Event published by API Gateway and grab the field that you want.
I have no clue over your header's name, but let's say you named it my-cool-header. It would then be accessible via event.headers['my-cool-header'] from within your Lambda function.
Your switch block would then become:
switch (token.toLowerCase())
case 'allow':
callback(null, generatePolicy('user', 'Allow', event.headers['my-cool-header']));
break;
case 'deny':
callback(null, generatePolicy('user', 'Deny', event.headers['my-cool-header']));
break;
case 'unauthorized':
callback("Unauthorized"); // Return a 401 Unauthorized response
break;
default:
callback("Error: Invalid token");
Similarly, if you wanted to send it on the body of your POST request, it would then be accessible via JSON.parse(event.body).myCoolField (body objects always come as stringified JSONs) and so on.
EDIT
I had missed one line on the original answer, which was trying to access event.authorizationToken - this is the same problem as the one cited above - therefore the code needs to be changed to const token = event.headers.authorizationToken if coming via Header, const token = JSON.parse(event.body).authorizationToken if coming from the body or const token = event.queryStringParameters.authorizationToken if coming from request parameters.
EDIT 2: The above fixed the issue. However, here's a simplified version of the code:
'use strict';
module.exports.handler = async (event) =>
const token = event.headers.authorizationToken;
switch (token.toLowerCase())
case 'allow':
return
statusCode: 200,
body: JSON.stringify(generatePolicy('user', 'Allow', event.headers.methodArn))
case 'deny':
return
statusCode: 200,
body: JSON.stringify(generatePolicy('user', 'Deny', event.headers.methodArn))
default:
return
statusCode: 400,
body: 'No token'
// Help function to generate an IAM policy
const generatePolicy = (principalId, effect, resource) =>
const authResponse = ;
authResponse.principalId = principalId;
if (effect && resource)
const policyDocument = ;
policyDocument.Version = '2012-10-17';
policyDocument.Statement = [];
const statementOne = ;
statementOne.Action = 'execute-api:Invoke';
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
// Optional output with custom properties of the String, Number or Boolean type.
authResponse.context =
"stringKey": "stringval",
"numberKey": 123,
"booleanKey": true
;
return authResponse;
Here's a proof of the working code:

As suggested by you I have used event.headers['methodArn'], but I am still getting the same error. The switch case "Default" has no event object in the callback(), so I do not think the problem is caused by the event.mehtodArn.
– KurioZ7
Mar 8 at 14:36
Well, that's because you now need to modify this line: event.authorizationToken and change it accordingly. Where is authorizationToken coming from? Header, Body, Request Param?
– Thales Minussi
Mar 8 at 14:37
The authorizationToken is sent in the header. I have replaced event.authorizationToken with event.headers[authorizationToken], but I am still getting the error.. I took the sample code from markpollmann.com/lambda-authorizer
– KurioZ7
Mar 8 at 14:41
He only tested it from AWS console (just like you were doing). What you can do for further troubleshooting is console.log(event) before you do anything so you can check where your field is coming from, but definitely event.authorizationToken won't work
– Thales Minussi
Mar 8 at 14:45
I can jump in on a chat if you want to.
– Thales Minussi
Mar 8 at 14:46
|
show 2 more comments
I have understood the reason why I was getting message = null for the invalid input. The default block in the switch case was using parameter "Error: Invalid token" in the callback() method. API Gateway only identifies "Allow", "Deny" and "Unauthorized" as valid values. These values are also case sensitive. If any string values other than these values are passed to the callback() method, then API Gateway will return message=null to the client.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55064760%2flambda-authorizer-not-returning-proper-error-message-with-callback-in-node-js%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You cannot simply access event.methodArn from your event object inside your Lambda function.
When you test it from the console, the exact JSON you are providing to your Lambda function is going to be injected in your event object, however, when the call is proxied through API Gateway, you will then need to access the Event published by API Gateway and grab the field that you want.
I have no clue over your header's name, but let's say you named it my-cool-header. It would then be accessible via event.headers['my-cool-header'] from within your Lambda function.
Your switch block would then become:
switch (token.toLowerCase())
case 'allow':
callback(null, generatePolicy('user', 'Allow', event.headers['my-cool-header']));
break;
case 'deny':
callback(null, generatePolicy('user', 'Deny', event.headers['my-cool-header']));
break;
case 'unauthorized':
callback("Unauthorized"); // Return a 401 Unauthorized response
break;
default:
callback("Error: Invalid token");
Similarly, if you wanted to send it on the body of your POST request, it would then be accessible via JSON.parse(event.body).myCoolField (body objects always come as stringified JSONs) and so on.
EDIT
I had missed one line on the original answer, which was trying to access event.authorizationToken - this is the same problem as the one cited above - therefore the code needs to be changed to const token = event.headers.authorizationToken if coming via Header, const token = JSON.parse(event.body).authorizationToken if coming from the body or const token = event.queryStringParameters.authorizationToken if coming from request parameters.
EDIT 2: The above fixed the issue. However, here's a simplified version of the code:
'use strict';
module.exports.handler = async (event) =>
const token = event.headers.authorizationToken;
switch (token.toLowerCase())
case 'allow':
return
statusCode: 200,
body: JSON.stringify(generatePolicy('user', 'Allow', event.headers.methodArn))
case 'deny':
return
statusCode: 200,
body: JSON.stringify(generatePolicy('user', 'Deny', event.headers.methodArn))
default:
return
statusCode: 400,
body: 'No token'
// Help function to generate an IAM policy
const generatePolicy = (principalId, effect, resource) =>
const authResponse = ;
authResponse.principalId = principalId;
if (effect && resource)
const policyDocument = ;
policyDocument.Version = '2012-10-17';
policyDocument.Statement = [];
const statementOne = ;
statementOne.Action = 'execute-api:Invoke';
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
// Optional output with custom properties of the String, Number or Boolean type.
authResponse.context =
"stringKey": "stringval",
"numberKey": 123,
"booleanKey": true
;
return authResponse;
Here's a proof of the working code:

As suggested by you I have used event.headers['methodArn'], but I am still getting the same error. The switch case "Default" has no event object in the callback(), so I do not think the problem is caused by the event.mehtodArn.
– KurioZ7
Mar 8 at 14:36
Well, that's because you now need to modify this line: event.authorizationToken and change it accordingly. Where is authorizationToken coming from? Header, Body, Request Param?
– Thales Minussi
Mar 8 at 14:37
The authorizationToken is sent in the header. I have replaced event.authorizationToken with event.headers[authorizationToken], but I am still getting the error.. I took the sample code from markpollmann.com/lambda-authorizer
– KurioZ7
Mar 8 at 14:41
He only tested it from AWS console (just like you were doing). What you can do for further troubleshooting is console.log(event) before you do anything so you can check where your field is coming from, but definitely event.authorizationToken won't work
– Thales Minussi
Mar 8 at 14:45
I can jump in on a chat if you want to.
– Thales Minussi
Mar 8 at 14:46
|
show 2 more comments
You cannot simply access event.methodArn from your event object inside your Lambda function.
When you test it from the console, the exact JSON you are providing to your Lambda function is going to be injected in your event object, however, when the call is proxied through API Gateway, you will then need to access the Event published by API Gateway and grab the field that you want.
I have no clue over your header's name, but let's say you named it my-cool-header. It would then be accessible via event.headers['my-cool-header'] from within your Lambda function.
Your switch block would then become:
switch (token.toLowerCase())
case 'allow':
callback(null, generatePolicy('user', 'Allow', event.headers['my-cool-header']));
break;
case 'deny':
callback(null, generatePolicy('user', 'Deny', event.headers['my-cool-header']));
break;
case 'unauthorized':
callback("Unauthorized"); // Return a 401 Unauthorized response
break;
default:
callback("Error: Invalid token");
Similarly, if you wanted to send it on the body of your POST request, it would then be accessible via JSON.parse(event.body).myCoolField (body objects always come as stringified JSONs) and so on.
EDIT
I had missed one line on the original answer, which was trying to access event.authorizationToken - this is the same problem as the one cited above - therefore the code needs to be changed to const token = event.headers.authorizationToken if coming via Header, const token = JSON.parse(event.body).authorizationToken if coming from the body or const token = event.queryStringParameters.authorizationToken if coming from request parameters.
EDIT 2: The above fixed the issue. However, here's a simplified version of the code:
'use strict';
module.exports.handler = async (event) =>
const token = event.headers.authorizationToken;
switch (token.toLowerCase())
case 'allow':
return
statusCode: 200,
body: JSON.stringify(generatePolicy('user', 'Allow', event.headers.methodArn))
case 'deny':
return
statusCode: 200,
body: JSON.stringify(generatePolicy('user', 'Deny', event.headers.methodArn))
default:
return
statusCode: 400,
body: 'No token'
// Help function to generate an IAM policy
const generatePolicy = (principalId, effect, resource) =>
const authResponse = ;
authResponse.principalId = principalId;
if (effect && resource)
const policyDocument = ;
policyDocument.Version = '2012-10-17';
policyDocument.Statement = [];
const statementOne = ;
statementOne.Action = 'execute-api:Invoke';
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
// Optional output with custom properties of the String, Number or Boolean type.
authResponse.context =
"stringKey": "stringval",
"numberKey": 123,
"booleanKey": true
;
return authResponse;
Here's a proof of the working code:

As suggested by you I have used event.headers['methodArn'], but I am still getting the same error. The switch case "Default" has no event object in the callback(), so I do not think the problem is caused by the event.mehtodArn.
– KurioZ7
Mar 8 at 14:36
Well, that's because you now need to modify this line: event.authorizationToken and change it accordingly. Where is authorizationToken coming from? Header, Body, Request Param?
– Thales Minussi
Mar 8 at 14:37
The authorizationToken is sent in the header. I have replaced event.authorizationToken with event.headers[authorizationToken], but I am still getting the error.. I took the sample code from markpollmann.com/lambda-authorizer
– KurioZ7
Mar 8 at 14:41
He only tested it from AWS console (just like you were doing). What you can do for further troubleshooting is console.log(event) before you do anything so you can check where your field is coming from, but definitely event.authorizationToken won't work
– Thales Minussi
Mar 8 at 14:45
I can jump in on a chat if you want to.
– Thales Minussi
Mar 8 at 14:46
|
show 2 more comments
You cannot simply access event.methodArn from your event object inside your Lambda function.
When you test it from the console, the exact JSON you are providing to your Lambda function is going to be injected in your event object, however, when the call is proxied through API Gateway, you will then need to access the Event published by API Gateway and grab the field that you want.
I have no clue over your header's name, but let's say you named it my-cool-header. It would then be accessible via event.headers['my-cool-header'] from within your Lambda function.
Your switch block would then become:
switch (token.toLowerCase())
case 'allow':
callback(null, generatePolicy('user', 'Allow', event.headers['my-cool-header']));
break;
case 'deny':
callback(null, generatePolicy('user', 'Deny', event.headers['my-cool-header']));
break;
case 'unauthorized':
callback("Unauthorized"); // Return a 401 Unauthorized response
break;
default:
callback("Error: Invalid token");
Similarly, if you wanted to send it on the body of your POST request, it would then be accessible via JSON.parse(event.body).myCoolField (body objects always come as stringified JSONs) and so on.
EDIT
I had missed one line on the original answer, which was trying to access event.authorizationToken - this is the same problem as the one cited above - therefore the code needs to be changed to const token = event.headers.authorizationToken if coming via Header, const token = JSON.parse(event.body).authorizationToken if coming from the body or const token = event.queryStringParameters.authorizationToken if coming from request parameters.
EDIT 2: The above fixed the issue. However, here's a simplified version of the code:
'use strict';
module.exports.handler = async (event) =>
const token = event.headers.authorizationToken;
switch (token.toLowerCase())
case 'allow':
return
statusCode: 200,
body: JSON.stringify(generatePolicy('user', 'Allow', event.headers.methodArn))
case 'deny':
return
statusCode: 200,
body: JSON.stringify(generatePolicy('user', 'Deny', event.headers.methodArn))
default:
return
statusCode: 400,
body: 'No token'
// Help function to generate an IAM policy
const generatePolicy = (principalId, effect, resource) =>
const authResponse = ;
authResponse.principalId = principalId;
if (effect && resource)
const policyDocument = ;
policyDocument.Version = '2012-10-17';
policyDocument.Statement = [];
const statementOne = ;
statementOne.Action = 'execute-api:Invoke';
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
// Optional output with custom properties of the String, Number or Boolean type.
authResponse.context =
"stringKey": "stringval",
"numberKey": 123,
"booleanKey": true
;
return authResponse;
Here's a proof of the working code:

You cannot simply access event.methodArn from your event object inside your Lambda function.
When you test it from the console, the exact JSON you are providing to your Lambda function is going to be injected in your event object, however, when the call is proxied through API Gateway, you will then need to access the Event published by API Gateway and grab the field that you want.
I have no clue over your header's name, but let's say you named it my-cool-header. It would then be accessible via event.headers['my-cool-header'] from within your Lambda function.
Your switch block would then become:
switch (token.toLowerCase())
case 'allow':
callback(null, generatePolicy('user', 'Allow', event.headers['my-cool-header']));
break;
case 'deny':
callback(null, generatePolicy('user', 'Deny', event.headers['my-cool-header']));
break;
case 'unauthorized':
callback("Unauthorized"); // Return a 401 Unauthorized response
break;
default:
callback("Error: Invalid token");
Similarly, if you wanted to send it on the body of your POST request, it would then be accessible via JSON.parse(event.body).myCoolField (body objects always come as stringified JSONs) and so on.
EDIT
I had missed one line on the original answer, which was trying to access event.authorizationToken - this is the same problem as the one cited above - therefore the code needs to be changed to const token = event.headers.authorizationToken if coming via Header, const token = JSON.parse(event.body).authorizationToken if coming from the body or const token = event.queryStringParameters.authorizationToken if coming from request parameters.
EDIT 2: The above fixed the issue. However, here's a simplified version of the code:
'use strict';
module.exports.handler = async (event) =>
const token = event.headers.authorizationToken;
switch (token.toLowerCase())
case 'allow':
return
statusCode: 200,
body: JSON.stringify(generatePolicy('user', 'Allow', event.headers.methodArn))
case 'deny':
return
statusCode: 200,
body: JSON.stringify(generatePolicy('user', 'Deny', event.headers.methodArn))
default:
return
statusCode: 400,
body: 'No token'
// Help function to generate an IAM policy
const generatePolicy = (principalId, effect, resource) =>
const authResponse = ;
authResponse.principalId = principalId;
if (effect && resource)
const policyDocument = ;
policyDocument.Version = '2012-10-17';
policyDocument.Statement = [];
const statementOne = ;
statementOne.Action = 'execute-api:Invoke';
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
// Optional output with custom properties of the String, Number or Boolean type.
authResponse.context =
"stringKey": "stringval",
"numberKey": 123,
"booleanKey": true
;
return authResponse;
Here's a proof of the working code:

edited Mar 8 at 15:41
answered Mar 8 at 14:21
Thales MinussiThales Minussi
1,510419
1,510419
As suggested by you I have used event.headers['methodArn'], but I am still getting the same error. The switch case "Default" has no event object in the callback(), so I do not think the problem is caused by the event.mehtodArn.
– KurioZ7
Mar 8 at 14:36
Well, that's because you now need to modify this line: event.authorizationToken and change it accordingly. Where is authorizationToken coming from? Header, Body, Request Param?
– Thales Minussi
Mar 8 at 14:37
The authorizationToken is sent in the header. I have replaced event.authorizationToken with event.headers[authorizationToken], but I am still getting the error.. I took the sample code from markpollmann.com/lambda-authorizer
– KurioZ7
Mar 8 at 14:41
He only tested it from AWS console (just like you were doing). What you can do for further troubleshooting is console.log(event) before you do anything so you can check where your field is coming from, but definitely event.authorizationToken won't work
– Thales Minussi
Mar 8 at 14:45
I can jump in on a chat if you want to.
– Thales Minussi
Mar 8 at 14:46
|
show 2 more comments
As suggested by you I have used event.headers['methodArn'], but I am still getting the same error. The switch case "Default" has no event object in the callback(), so I do not think the problem is caused by the event.mehtodArn.
– KurioZ7
Mar 8 at 14:36
Well, that's because you now need to modify this line: event.authorizationToken and change it accordingly. Where is authorizationToken coming from? Header, Body, Request Param?
– Thales Minussi
Mar 8 at 14:37
The authorizationToken is sent in the header. I have replaced event.authorizationToken with event.headers[authorizationToken], but I am still getting the error.. I took the sample code from markpollmann.com/lambda-authorizer
– KurioZ7
Mar 8 at 14:41
He only tested it from AWS console (just like you were doing). What you can do for further troubleshooting is console.log(event) before you do anything so you can check where your field is coming from, but definitely event.authorizationToken won't work
– Thales Minussi
Mar 8 at 14:45
I can jump in on a chat if you want to.
– Thales Minussi
Mar 8 at 14:46
As suggested by you I have used event.headers['methodArn'], but I am still getting the same error. The switch case "Default" has no event object in the callback(), so I do not think the problem is caused by the event.mehtodArn.
– KurioZ7
Mar 8 at 14:36
As suggested by you I have used event.headers['methodArn'], but I am still getting the same error. The switch case "Default" has no event object in the callback(), so I do not think the problem is caused by the event.mehtodArn.
– KurioZ7
Mar 8 at 14:36
Well, that's because you now need to modify this line: event.authorizationToken and change it accordingly. Where is authorizationToken coming from? Header, Body, Request Param?
– Thales Minussi
Mar 8 at 14:37
Well, that's because you now need to modify this line: event.authorizationToken and change it accordingly. Where is authorizationToken coming from? Header, Body, Request Param?
– Thales Minussi
Mar 8 at 14:37
The authorizationToken is sent in the header. I have replaced event.authorizationToken with event.headers[authorizationToken], but I am still getting the error.. I took the sample code from markpollmann.com/lambda-authorizer
– KurioZ7
Mar 8 at 14:41
The authorizationToken is sent in the header. I have replaced event.authorizationToken with event.headers[authorizationToken], but I am still getting the error.. I took the sample code from markpollmann.com/lambda-authorizer
– KurioZ7
Mar 8 at 14:41
He only tested it from AWS console (just like you were doing). What you can do for further troubleshooting is console.log(event) before you do anything so you can check where your field is coming from, but definitely event.authorizationToken won't work
– Thales Minussi
Mar 8 at 14:45
He only tested it from AWS console (just like you were doing). What you can do for further troubleshooting is console.log(event) before you do anything so you can check where your field is coming from, but definitely event.authorizationToken won't work
– Thales Minussi
Mar 8 at 14:45
I can jump in on a chat if you want to.
– Thales Minussi
Mar 8 at 14:46
I can jump in on a chat if you want to.
– Thales Minussi
Mar 8 at 14:46
|
show 2 more comments
I have understood the reason why I was getting message = null for the invalid input. The default block in the switch case was using parameter "Error: Invalid token" in the callback() method. API Gateway only identifies "Allow", "Deny" and "Unauthorized" as valid values. These values are also case sensitive. If any string values other than these values are passed to the callback() method, then API Gateway will return message=null to the client.
add a comment |
I have understood the reason why I was getting message = null for the invalid input. The default block in the switch case was using parameter "Error: Invalid token" in the callback() method. API Gateway only identifies "Allow", "Deny" and "Unauthorized" as valid values. These values are also case sensitive. If any string values other than these values are passed to the callback() method, then API Gateway will return message=null to the client.
add a comment |
I have understood the reason why I was getting message = null for the invalid input. The default block in the switch case was using parameter "Error: Invalid token" in the callback() method. API Gateway only identifies "Allow", "Deny" and "Unauthorized" as valid values. These values are also case sensitive. If any string values other than these values are passed to the callback() method, then API Gateway will return message=null to the client.
I have understood the reason why I was getting message = null for the invalid input. The default block in the switch case was using parameter "Error: Invalid token" in the callback() method. API Gateway only identifies "Allow", "Deny" and "Unauthorized" as valid values. These values are also case sensitive. If any string values other than these values are passed to the callback() method, then API Gateway will return message=null to the client.
answered Mar 9 at 16:27
KurioZ7KurioZ7
2,64852341
2,64852341
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55064760%2flambda-authorizer-not-returning-proper-error-message-with-callback-in-node-js%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown