api 网关端点与 cognito 授权者 cros 错误?

时间:2021-04-23 14:13:08

标签: cors aws-api-gateway amazon-cognito

我正在使用带有 cognito 的 API 网关来授权一个 GET 端点。 如果我通过邮递员(node\python 代码)运行它,效果很好。 但是当我在 CHROME 中运行 React 应用程序时,我得到了 Access to XMLHttpRequest at 'my path' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

关于我的 api 网关 API 的详细信息

  1. 带有 cognito 授权器的 GET 请求,期望一个 Authorization 标头
  2. 获取请求具有返回以下标头的 lambda 代理
"headers": {
            'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
            "Access-Control-Allow-Credentials": 'true',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'OPTIONS, GET, POST',
        },
  1. 没有认知授权者的 OPTIONS 方法
  2. 我在端点上启用了 CORS。

结果:

  1. 在 GET 上没有 cognito 它可以工作 -> 我将内容输入到我的 React 应用程序中
  2. 当我添加 cognito auth 时,我收到 CORS 错误
  3. 我在运行 curl -v -X OPTIONS https://<mypath> 时看到的异常是
* Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
< HTTP/2 401 
< date: Mon, 26 Apr 2021 08:03:37 GMT
< content-type: application/json
< content-length: 26
< x-amzn-requestid: 5f305d7d-70cc-4751-81f5-581345521f00
< x-amzn-errortype: UnauthorizedException
< x-amz-apigw-id: eYcKEHB2vHcFSLw=
< 

  1. 我正在运行的反应代码是:
import axios from "axios";
const value = <my id token>
const url1 = "https:...."
const headers ={
  "Authorization": value,
}
function getPoints(){
   axios.get(
    url1, headers
  ).then((response) => {
    console.log("sucessssssss");
    console.log(response)
    // console.log(response.json());
  }, (error) => {
    console.log("errorrrrr");
    console.log(error);
  }); 
}

function App() {
  return (
    <div className="App">
      {getPoints()}
      cors test
    </div>
  );
}

export default App;

任何想法我做错了什么?任何帮助\提示都会有所帮助 谢谢

1 个答案:

答案 0 :(得分:0)

CORS 标头 (Access-Control-Allow-*) 是响应标头。您不应在请求中指定它们。

API Gateway 有一个您应该使用的 out-of-the-box CORS handler

如果您决定仍要使用自己的处理程序,请确保在将 Cognito 授权方设置为默认授权方时,明确OPTIONS 方法上设置授权方NONE 授权人。