In order to prevent users who have not logged in to call my lambda function through the AWS API Gateway, I'm using the Custom Authorizer lambda solution.
If the request is authorized (200) and I get a response from the called lambda everything works fine and I get the Access-Control-Allow-Origin
header.
But if the request is not authorized, I get a 401 that has no Access-Control-Allow-Origin
header, therefore preventing me from reading the 401 status of the response and redirecting the user to the log-in page.
I believe this is because the Custom Autorization mechanism is unaware that the request needs to use CORS. Does anyone know that this is actually the issue? Are you aware of any possible solution?
I'm happy to announce the new Gateway Responses feature which allows you to customize the error responses for requests that don't call your integration. This allows you to ensure that CORS headers are included, even on failed auth requests.
Read more in our documentation, which includes a CORS example.
Yes, this is a known bug with API Gateway custom authorizers. Thanks for bringing this to our attention. The team will update this post when we've deployed a fix. Apologies for the inconvenience.
The easiest way to resolve this for all 4XX error (including 401 errors) is to go to "Gateway Responses" and then select "Default 4XX" and then add the the header "Access-Control-Allow-Origin" with the value '*'.
See screenshot:
Adding to the answers above, if you're not using Cloudformation/SAM template, you can save yourself some manual steps using this python script:
Because it took me a while to figure out how to put it all together in Cloud Formation, here is a snippet showing how to set it up.
This works for me (inline in AWS::APIGateway: definition)
The available GatewayResponses Naming are:
So you could specify the Response customization for these Controlled AWS responses.