簡體   English   中英

向AWS Gateway API發出請求React Native

[英]Making requests to AWS Gateway API React Native

在我的應用程序中,用戶可以通過AWS Cognito用戶池或Facebook進行身份驗證,所有人都可以管理AWS身份池。 這一切都正常,用戶可以成功登錄和驗證。 現在,我需要向AWS Gateway API發出經過身份驗證的請求,然后觸發Lambda函數。 我對接下來會發生什么感到困惑。 我是否需要編寫代碼來簽署這些請求,或者AWS javascript SDK是否已經內置了這些內容? 我需要創建一個授權人嗎? 如何從AWS.config.credentials轉到對Gateway API進行成功的,經過身份驗證的請求?

我正在使用React Native,因此自動生成的API將無法正常工作。

編輯:這是我的請求代碼:

fetch('https://MY_API_GATEWAY_URL/prod/handleMessages/', { method: 'GET', body: null, headers: { Authorization: 'Bearer ' + this.state.token, /* this is the JWT token from AWS Cognito. */ }, }) .then((response) => { alert(JSON.stringify(response, null, 2)) })

我從此得到403響應,但異常:IncompleteSignatureException

此時,您應該擁有有效的Cognito頒發的JWT。 要在AWS API Gateway后面調用API,您需要將JWT與API調用一起傳遞。 這應該在具有Bearer類型的Authorization標頭中。 您可以確定是否需要自定義授權程序,或者僅使用API​​網關的內置授權。

其他信息可以在這里找到 - http://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html

您還需要確保IAM規則到位以允許UserPool訪問API網關端點 - http://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html

在AWS Cognito UserPools身份驗證之后,您可以使用API​​網關端點從服務器端生成JWT令牌。 例如/<stage>/authenticate

var authenticationData = {
    Username : 'username',
    Password : 'password',
};
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
var poolData = { UserPoolId : 'us-east-1_TcoKGbf7n',
    ClientId : '4pe2usejqcdmhi0a25jp4b5sh3'
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var userData = {
    Username : 'username',
    Pool : userPool
};
var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: function (result) {
        console.log('access token + ' + result.getAccessToken().getJwtToken());
        /*Use the idToken for Logins Map when Federating User Pools with Cognito Identity or when passing through an Authorization Header to an API Gateway Authorizer*/
        console.log('idToken + ' + result.idToken.jwtToken);
    },

    onFailure: function(err) {
        alert(err);
    },

});

有關更多詳細信息,請查看此示例

在身份驗證之后,將jwtToken發送回React Native應用程序,在該應用程序中,需要在Authorization標頭中發送該標記以及后續API請求的標記。

在API網關中,在集成方法配置中配置用戶池授權程序,以便它自動驗證授權標頭並加載端點的用戶上下文信息。

您可以使用AWS Amplify庫的API模塊自動簽署請求: https//github.com/aws/aws-amplify

對於React Native,這可以通過npm獲得:

npm install aws-amplify-react-native

如果使用Cognito User Pools鏈接庫,如下所示: https//github.com/aws/aws-amplify/blob/master/media/quick_start.md#react-native-development

API模塊將讓您為端點配置友好名稱,並從API網關階段配置調用URL。 然后,您只需調用HTTP方法並將可選參數作為選項傳遞:

import Amplify, {API} from 'aws-amplify-react-native';
Amplify.configure('your_config_file_here');
API.get('apiname', 'invokeURL', options).then(res=>{
    console.log(res);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM