How to return a 401 Unauthorized response from AWS Custom Lambda Authorizer
- 1 minIf you are using the async handler then, to return a 401 you have to:
- Set Lambda Environment Variable UNWRAP_AGGREGATE_EXCEPTIONS to 1 (Only if you are using the async handler)
- throw exceptions with a message starting with “Unauthorized”
So for the following async Handler:
The environment variable is set as follows:
Why?
Seems as though Amazon’s Api gateway uses a regex expression to look for the word “Unauthorized”[1]. However, when exceptions are thrown by AWS Lambda, then they are wrapped in an AggregateException[2] and needs to be unwrapped.
References:
[1] https://github.com/aws/aws-lambda-dotnet/issues/293
[2] https://hackernoon.com/how-to-unwrap-an-aggregateexception-thrown-by-aws-lambda-6652fd085952