React Native AWS-amplify在请求中包含cognito Authorization头

mspsb9vt  于 2023-06-30  发布在  React
关注(0)|答案(2)|浏览(144)

我创建了一个AWS移动的中心项目,包括Cognito和Cloud逻辑。在我的API网关中,我为授权者设置了Cognito用户池。我使用React Native作为我的客户端应用程序。如何将Authorization标头添加到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);
  });
};
a1o7rhls

a1o7rhls1#

默认情况下,aws-amplify的API模块将尝试对请求进行sig4签名。如果您的授权器类型为AWS_IAM,则此功能非常有用。
这显然不是你在使用Cognito用户池授权器时想要的。在这种情况下,您需要在Authorization头中传递id_token,而不是sig4签名。
现在,您确实可以传递Authorization头来放大,以及it will no longer overwrite it with the sig4 signature
在本例中,您只需要将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-amplify 0.4.1进行测试。

dfty9e19

dfty9e192#

只有当你的端点没有aws_iam授权时,接受的答案才有效,否则你会遇到IncompleteSignatureException。解决方案是将id_token附加到自定义头(例如:jwt-token),并记住在apigateway中将自定义头加入白名单。

相关问题