Invalid security token included in the request. aws js sdk

I posted here on the AWS forum

I am using aws-js-sdk v2.2.3 with the following code. I am returning data with credentials filled in. When I try to use credentials, I get an error that they are not valid. I use a stream of authenticated developer identifiers. I have two roles Auth and UnAuth. My personal pool looks right. Trust relationships look like they point to the correct identifier pool identifier. There are policies related to the Auth role for S3 and DynamoDB. I'm at a loss. Any help would be greatly appreciated.

javascript client side:

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);
    });

I complete Id and SecretKey and they fill up.

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;
}
+4
2

Cognito AWS, AWS.CognitoIdentityCredentials Javascript SDK API-.

AWS.CognitoIdentityCredentials Cognito:

+2

: CognitoIdentityCredentials IdentityId, IDentityId , (Facebook, Google, 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
                                    });

                                }
                        });
            }
        });

});

NB: , API Gateway, , , , , .

, IAM, , , .

, , , , .

STS.assumeRoleWithWebIdentity , , AWS JS SDK, iOS android/java Boto, STS.assumeRole.

, .

+1

Source: https://habr.com/ru/post/1610324/


All Articles