Introduction
While developing an Alexa Skill for my Work using a custom Endpoint to a Laravel-Backend system, because of Amazons strict Security requirements, I faced major problems getting the validation right. Due to the lack of documentation by Amazon or basically anyone else.
I worked on this for quite a while even though the final solution seems quite simple.
The solution now worked for 1 month with continuous use by around 250 users without any errors. So it seems that it is safe to assume that it works properly.
Using the Code
This is the Laravel function.
$request
is a Request
object by Laravel.
public static function validateRequest($request)
{
$data = json_decode($request->getContent(), false);
if (!$request->hasHeader("SignatureCertChainUrl") | !$request->hasHeader("Signature"))
return false;
$certificateUri = $request->header("SignatureCertChainUrl");
$uriParts = parse_url($certificateUri);
if (strcasecmp($uriParts["scheme"], "https") != 0)
return false;
if (strcasecmp($uriParts["host"], "s3.amazonaws.com") != 0)
return false;
if (array_key_exists("port", $uriParts) && $uriParts["port"] != "443")
return false;
if (strpos($uriParts["path"], "/echo.api/") !== 0)
return false;
$certificateName = "certificates\\" . array_last(explode("/", $uriParts["path"]));
if (!Storage::disk("alexa")->exists($certificateName))
Storage::disk("alexa")->put($certificateName, file_get_contents($certificateUri));
$certificateFile = Storage::disk("alexa")->get($certificateName);
$certificateData = openssl_x509_parse($certificateFile);
$validFrom = date("Y-m-d H:i:s", $certificateData["validFrom_time_t"]);
$validTo = date("Y-m-d H:i:s", $certificateData["validTo_time_t"]);
$san = substr($certificateData["extensions"]["subjectAltName"],
strpos($certificateData["extensions"]["subjectAltName"], ":") + 1);
if (!Carbon::now()->between(Carbon::parse($validFrom), Carbon::parse($validTo)))
return false;
if ($san != "echo-api.amazon.com")
return false;
$publicKey = openssl_get_publickey(openssl_x509_read($certificateFile));
$signature = base64_decode($request->header("Signature"), true);
$hash1Binary = null;
openssl_public_decrypt($signature, $hash1Binary, $publicKey);
$hash1 = substr(bin2hex($hash1Binary), 30);
$hash2 = sha1($request->getContent());
if ($hash1 != $hash2)
return false;
if (!Carbon::now() > Carbon::createFromFormat("Y-m-d\TH:i:s\Z", $data->request->timestamp))
return false;
return true;
}