简体   繁体   English

AWS API 网关和授权方 CORS 错误

[英]AWS API gateway and authorizer CORS error

It took me awhile to realized it's not a CORS issue.我花了一段时间才意识到这不是 CORS 问题。 I have Cognito authorizer setup with my API Gateway.我的 API 网关设置了 Cognito 授权方。 I test with the my IDtoken using Postman, when the authorizer on my header is incorrect or the token is expired, postman response would tell me我使用 Postman 测试我的 IDtoken,当我的 header 上的授权人不正确或令牌已过期时,postman 响应会告诉我

{
    "message": "Unauthorized" 
}
{
        "message": "Token expired" 
   }

The problem is, in my dev/localhost;问题是,在我的 dev/localhost 中; I would get the results correctly if the token is correct, but when the token is bad or expired, I get a CORs error.如果令牌正确,我会正确地得到结果,但是当令牌错误或过期时,我会收到 CORs 错误。 How do I set this up so I can handle the results correctly?我该如何设置才能正确处理结果?

Access to XMLHttpRequest at 'https://xcz3vfg4n7.execute-api.us-west-2.amazonaws.com/prod' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhr.js:210          POST https://xcz3vfg4n7.execute-api.us-west-2.amazonaws.com/prod net::ERR_FAILED 403

We ran into this same issue and since it was a painful to resolve, thought I would type up the solution.我们遇到了同样的问题,因为解决起来很痛苦,所以我想我会输入解决方案。

Specifically we were receiving the CORs error via Axios in our React app, but not getting the error through cURL or Thunderclient (Postman-like extension for VS Code).具体来说,我们在 React 应用程序中通过 Axios 收到了 CORs 错误,但没有通过 cURL 或 Thunderclient(VS Code 的类似 Postman 的扩展)收到错误。

The resolution was actually missing headers on the "response" object from API Gateway.该解决方案实际上缺少来自 API 网关的“响应”object 的标头。

Since cURL and Thunderclient/Postman don't care about CORs (because they server-based, not browser-based), those tools don't look for the 'Access-Control-Allow-Origin' header in the response.由于 cURL 和 Thunderclient/Postman 不关心 CORs(因为它们基于服务器,而不是基于浏览器),这些工具不会在响应中查找“Access-Control-Allow-Origin”header。

We got back our preflight Options call 200 just fine, and then realized that the POST call was returning the 401 without an 'Access-Control-Allow-Origin' header.我们恢复了预检选项调用 200 就好了,然后意识到 POST 调用返回的是 401 而没有“Access-Control-Allow-Origin”header。

Since the Authorizer is on the Method Request, it never goes past the Lambda proxy in the API Gateway and thus doesn't return full response headers.由于授权方在方法请求上,它永远不会通过 API 网关中的 Lambda 代理,因此不会返回完整的响应标头。

So... the solution was actually really simple.所以...解决方案实际上非常简单。

  1. Go into "Gateway Responses" Go 进入“网关响应”
  2. Choose the "Unauthorized" option选择“未经授权”选项
  3. Add the response headers (see screenshot)添加响应标头(见屏幕截图)

IMPORTANT: Don't forget to "Redeploy" your API or the changes won't take effect重要提示:不要忘记“重新部署”您的 API,否则更改不会生效

Example:例子: API 网关响应示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM