0

有人可以告诉我为什么下面的 php 代码会导致 InvalidClientTokenId 错误,我有点茫然。角色已分配给具有适当权限的此 EC2 实例。请原谅格式和标准,它已被简化和最小化以服务于这个简单的测试用例。

// get role credentials
$role_name = file_get_contents('http://169.254.169.254/latest/meta-data/iam/security-credentials/');
$auth = json_decode(file_get_contents('http://169.254.169.254/latest/meta-data/iam/security-credentials/'.$role_name),true);
print_r($auth);

// fixed params
$params = array();
$params['AWSAccessKeyId']     = $auth['AccessKeyId'];
$params['SignatureMethod']    = 'HmacSHA256';
$params['SignatureVersion']  =  '2';
$params['Timestamp']          = gmdate('Y-m-d\TH:i:s\Z');

// SDB API
$params['Version']            = '2009-04-15';
$params['Action']             = 'Select';
$params['SelectExpression']  =  'select * from `MYSDBDOMAIN`';

// format params into a string according to aws requirements
uksort($params, 'strcmp'); $params_str = '';
foreach ($params as $key => $val){ $params_str .= rawurlencode($key).'='.rawurlencode($val).'&'; }
$params_str = str_replace('%7E', '~',$params_str);  $params_str = substr($params_str, 0, -1);

// create signature
$signature = urlencode(base64_encode(hash_hmac('sha256', "GET\nsdb.ap-southeast-1.amazonaws.com\n/\n".$params_str, $auth['SecretAccessKey'], true)));

// create full url
$url = "https://sdb.ap-southeast-1.amazonaws.com/?$params_str&Signature=$signature";

// Initiate curl and set options
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: keep-alive', 'Keep-Alive: 300', 'x-amz-security-token: '.$auth['Token']));

// get the result into an array and print
$result = json_decode(json_encode(simplexml_load_string(curl_exec($ch))),true);
print_r($result);

这导致:

Array
(
    [Code] => Success
    [LastUpdated] => 2013-10-18T02:31:12Z
    [Type] => AWS-HMAC
    [AccessKeyId] => +MYACCESSKEY+
    [SecretAccessKey] => +MYSECRET+
    [Token] => +MYTOKEN+
    [Expiration] => 2013-10-18T09:04:14Z
)


Array
(
    [Errors] => Array
        (
            [Error] => Array
                (
                    [Code] => InvalidClientTokenId
                    [Message] => The AWS Access Key Id you provided does not exist in our records.
                )

        )

    [RequestID] => d0a23941-b9ff-ab89-e357-ab8122ee7307
)

谢谢

4

1 回答 1

0

这就是解决方案。需要添加 SecurityToken 参数:

$params['SecurityToken'] = $auth['Token'];
于 2013-10-25T00:31:58.953 回答