我正在尝试连接到外部API,更具体地说是在这里复制此Ruby代码:working code。我的 env 变量是正确的,也就是说,如果我更改它们,则会收到“找不到帐户”响应。如果我使用上面链接中提供的Ruby代码,则可以使用。
$date = new \DateTime(now());
$date->setTimezone(new \DateTimeZone('Europe/Athens'));
# Generates a date in this format: Wed, 21 Nov 2018 22:37:14 GMT
$date = $date->format(\DateTime::RFC7231);
$body = [
'data' => [
'type' => 'profile'
]
];
$request_target = 'post /profiles';
# Generates a digest using the request body
$digest = 'SHA-256=' . base64_encode(hash('sha256', json_encode($body), true));
$content_type = 'application/vnd.api+json';
$accept_type = 'application/vnd.api+json';
$version = '2016-09-01';
# Generates the signing string. Note that the parts of the string are
# concatenated with a newline character
$signing_string = implode('\n', [
"(request-target): {$request_target}",
"date: {$date}",
"digest: {$digest}"
]);
# Creates the HMAC-SHA256 digest using the API secret and then base64
# encodes that value
$signature = trim(base64_encode(hash_hmac('sha256', $signing_string, env('COGNITO_SECRET'), true)));
# Creates the authorization header and concatenates it together using
# a comma
$authorization = implode(',', [
'Signature keyId="' . env('COGNITO_API_KEY') .'"',
'algorithm="hmac-sha256"',
'headers="(request-target) date digest"',
'signature="' . $signature . '"'
]);
$headers = [
'Content-Type' => $content_type,
'Cognito-Version' => $version,
'Accept' => $accept_type,
'Date' => $date,
'Digest' => $digest,
'Authorization' => $authorization,
];
try {
# Put everything together and execute the request. Note that the headers
# are defined in the same order as they are defined in the Authorization
# header above. They can be in any order, but they must be consistent.
$client = new Client();
$response = $client->post(env('COGNITO_ENDPOINT') . '/profiles', [
RequestOptions::HEADERS => $headers,
RequestOptions::JSON => $body,
//'debug' => true
]);
} catch (RequestException $e) {
return $this->respondWithGeneralError(json_decode($e->getResponse()->getBody()));
}catch (\Exception $e){
return $this->respondWithGeneralError($e->getMessage());
}
return $this->respondWithSuccess('auth', $response);
但是我无法创建正确的签名,因为我收到来自端点的未能验证请求签名的响应。
任何人都可以在我的代码中发现任何错误或错位吗?
答案 0 :(得分:0)
我认为这是个问题
$signing_string = implode('\n'
您对引号有误,需要使用双引号