11

我创建了一个包含 Cognito 和云逻辑的 AWS 移动中心项目。在我的 API 网关中,我为授权者设置了 Cognito 用户池。我使用 React Native 作为我的客户端应用程序。如何将授权标头添加到我的 API 请求中。

const request = {
  body: {
    attr: value
  }
};

API.post(apiName, path, request)
  .then(response => {
  // Add your code here
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
};
4

1 回答 1

25

默认情况下,API 模块aws-amplify会尝试对请求进行 sig4 签名。如果您的 Authorizer 类型是 ,那就太好了AWS_IAM

这显然不是您在使用 Cognito 用户池授权器时想要的。在这种情况下,您需要在Authorization标头中传递 id_token,而不是 sig4 签名。

今天确实可以传一个Authorizationheader来放大,不会再用sig4签名覆盖了


在您的情况下,您只需要将对象添加headers到您的request对象中。例如:

async function callApi() {

    // You may have saved off the JWT somewhere when the user logged in.
    // If not, get the token from aws-amplify:
    const user = await Auth.currentAuthenticatedUser();
    const token = user.signInUserSession.idToken.jwtToken;

    const request = {
        body: {
            attr: "value"
        },
        headers: {
            Authorization: token
        }
    };

    var response = await API.post(apiName, path, request)
        .catch(error => {
            console.log(error);
        });

    document.getElementById('output-container').innerHTML = JSON.stringify(response);
}

使用aws-amplify0.4.1 测试。

于 2018-06-02T17:43:43.160 回答