AWS-amplify在请求中包含Cognito Authorization标头 [英] AWS-amplify Including the cognito Authorization header in the request

查看:184
本文介绍了AWS-amplify在请求中包含Cognito Authorization标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have create an AWS mobile hub project including the Cognito and Cloud logic. In my API gateway, I set the Cognito user pool for the Authorizers. I use React native as my client side app. How can I add the Authorization header to my API request.

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

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


推荐答案

默认情况下,<$ c $的API模块c> aws-amplify 将尝试签名信号。如果您的授权者类型为 AWS_IAM ,那就太好了。

By default, the API module of aws-amplify will attempt to sig4 sign requests. This is great if your Authorizer type is AWS_IAM.

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

This is obviously not what you want when using a Cognito User Pool Authorizer. In this case, you need to pass the id_token in the Authorization header, instead of a sig4 signature.

Today ,您确实可以传递 Authorization 标头进行放大,并它将不再使用sig4签名覆盖它。

Today, you can indeed pass an Authorization header to amplify, and it will no longer overwrite it with the sig4 signature.

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

In your case, you just need to add the headers object to your request object. For example:

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。

这篇关于AWS-amplify在请求中包含Cognito Authorization标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆