4

我發佈了here on the AWS forum請求中包含的安全令牌無效。 aws js sdk

我在下面的代碼中使用了aws-js-sdk v2.2.3。我收到的數據與Credentials填充。當我嘗試使用憑據時,我收到錯誤信息,證明它們無效。我正在使用開發人員身份驗證流程。我有兩個角色Auth & UnAuth。我的身份池看起來是正確的。信任關係看起來像是指向正確的身份池ID。 DynamoDB中存在針對S3 &的Auth角色的策略。我很茫然。任何幫助,將不勝感激。

JavaScript客戶端:

var cognitoidentity = new AWS.CognitoIdentity({region: 'us-east-1'}); 
    var params = { 
     IdentityId: user.cognito_id, 
     Logins: { 
    'cognito-identity.amazonaws.com': user.cognito_token 
     } 
    }; 
    cognitoidentity.getCredentialsForIdentity(params, function(err, data) { 
     if (err) console.log(err, err.stack); // an error occurred 
     else console.log(data.Credentials); 
    }); 

我CONSOLE.LOG的Id &中SecretKey它們填充在

var aws_creds = StateService.get('user').aws_creds; 
console.log(aws_creds.AccessKeyId); 
console.log(aws_creds.SecretKey); 
AWS.config.update({ accessKeyId: aws_creds.AccessKeyId, 
      secretAccessKey: aws_creds.SecretKey, 
      endpoint: ENV.aws_dyndb_endpoint, 
      region: 'us-east-1' 
      }); 
var dynamodb = new AWS.DynamoDB(); 


console.log("user obj: ", StateService.get('user')); 
var params = { 
    TableName: games_table_name, 
    KeyConditionExpression: "Id = :v1", 
    ExpressionAttributeValues: { 
     ":v1": {"N": id} 
    } 
}; 

return dynamodb.query(params); 

我的解決方案
我想出什麼樣的主意是明確刷新憑證,而不是在我爲實例創建DynamoDb對象時懶惰地獲取憑證。這是我使用的函數,當刷新憑證時,返回承諾&。

refresh: function() { 
    var deferred = $q.defer(); 
    AWS.config.region = 'us-east-1'; 
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({ 
     IdentityPoolId: COGNITO_IDENTITY_POOL_ID, 
     IdentityId: COGNITO_ID, 
     Logins: 'cognito-identity.amazonaws.com' 
    }); 

    AWS.config.credentials.refresh(function(error) { 
     if ((error === undefined) || (error === null)) { 
     $log.debug("Credentials Refreshed Success: ", AWS.config.credentials); 
     var params = { 
      region: 'us-east-1', 
      apiVersion: '2012-08-10', 
      credentials: AWS.config.credentials 
     }; 

     $rootScope.dynamodb = new AWS.DynamoDB({params: params}); 
     deferred.resolve(); 
     } 
     else { 
     $log.debug("Error refreshing AWS Creds:, ", error); 
     deferred.reject(error); 
     } 
    }); 

    return deferred.promise; 
} 
+0

保存getCredentialsForIdentity()響應的代碼在哪裏?在失敗的操作中實際使用這些憑據的代碼在哪裏? – jarmod

回答

2

如果你想使用Cognito憑據來調用其他AWS服務,我建議你使用高級AWS.CognitoIdentityCredentials對象從JavaScript SDK,而不是直接調用服務API。

您可以找到有關如何初始化和Cognito開發者指南中使用AWS.CognitoIdentityCredentials更多信息: Developer Authenticated Identities

阿爾伯特

+1

我也有使用CognitoIdentityCredentials對象的相同問題。最終,它仍然會出現安全令牌無效的錯誤。 –

+0

@StephenBurke你有沒有想過這個錯誤你的問題?我收到無效的安全令牌錯誤 –

+0

@BenDavis我用我的解決方案編輯了原始帖子。頂部的AWS論壇鏈接中還有更多信息。最終對我來說,我需要設置一個區域並顯式刷新憑證。 –

1

流程是這樣的:你問CognitoIdentityCredentialsIdentityId的IDentityId是應該追蹤跨設備和身份提供者(如Facebook,谷歌,TWitter等)的用戶,然後使用該ID請求您附加角色CognitoIdentity,獲得令牌後,您可以要求STS.assumeRoleWithWebIdentity作爲臨時具有適當角色的證書通過你的杆子。

這裏是我是如何做的一個例子:

// set the Amazon Cognito region 
AWS.config.region = 'us-east-1'; 

// initialize the Credentials object with our parameters 
AWS.config.credentials = new AWS.CognitoIdentityCredentials({ 
    IdentityPoolId: 'us-east-1:YMIDENTITYPOLEID', 
}); 

// We can set the get method of the Credentials object to retrieve 
// the unique identifier for the end user (identityId) once the provider 
// has refreshed itself 
AWS.config.credentials.get(function(err) { 
    if (err) { 
     console.log("Error: "+err); 
     return; 
    } 
    console.log("Cognito Identity Id: " + AWS.config.credentials.identityId); 

     params = { 
      IdentityId: AWS.config.credentials.identityId 
     } 

    // Other service clients will automatically use the Cognito Credentials provider 
    // configured in the JavaScript SDK. 

     // Get the Role associated with the id coming from the pool 
     var cognitoidentity = new AWS.CognitoIdentity(); 

     cognitoidentity.getOpenIdToken(params, function(err, data) { 
      if (err){ 
       console.log(err, err.stack); // an error occurred 
      }else{ 
         // Get temporoarly credientials form STS to access the API 
         var params = { 
          RoleArn: 'ROLE_OF_YOUR_POLE_ARN', /* required */ 
          RoleSessionName: 'WHATEVERNAME', /* required */ 
          WebIdentityToken: data.Token, /* required */ 
         }; 

         var sts = new AWS.STS() 

         console.log(data);   // successful response 
         console.log(data.Token) 

         sts.assumeRoleWithWebIdentity(params, function(err, data) { 
           if (err){ 
             console.log(err, err.stack); // an error occurred 
           }else{ 
             console.log(data);   // successful response 
             // Now we need these credentials that we got for this app and for this user 
             // From here we can limit the damage by 
             // Burst calling to the API Gateway will be limited since we now that this is a single user on a single device 
             // If suspicious activities we can drop this user/device 
             // The privileges are limited since the role attached to this is only the API GateWay calling 
             // This creds are temporary they will expire in 1h 

             var apigClient = apigClientFactory.newClient({ 
              accessKey: data.Credentials.AccessKeyId, 
              secretKey: data.Credentials.SecretAccessKey, 
              sessionToken: data.Credentials.Token, //OPTIONAL: If you are using temporary credentials you must include the session token 
              region: AWS.config.region // OPTIONAL: The region where the API is deployed, by default this parameter is set to us-east-1 
             }); 

             // Call the get to test 
             apigClient.deviceGet({}, {}) 
            .then(function(result){ 
             //This is where you would put a success callback 
               console.log(result) 
            }).catch(function(result){ 
             //This is where you would put an error callback 
            }); 

           } 
         }); 
      } 
     }); 

}); 

注:這是一個測試,以獲取訪問API網關服務,但它不是不同的以訪問其他服務,這取決於在杆上配置它及其附加服務。

如果您擁有在IAM中創建的用戶的憑證,則不需要臨時標記,但是如果使用此流程,則必須包含它。

還有一點,限制您對杆子上的服務的訪問,請記住這是一個公開給定的鍵,每個人都可以使用它來訪問您的東西。

使用STS.assumeRoleWithWebIdentity是因爲我們在Web上,在AWS JS SDK中,如果使用iOS或android/java或Boto,則必須使用STS.assumeRole。

希望這會有所幫助。

相關問題