Created
June 18, 2021 08:55
-
-
Save coreymcmahon/9a38bbfc71d915d8302d5687682c0f93 to your computer and use it in GitHub Desktop.
Hmac webhook verification
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Http\Request; | |
class HmacVerifier | |
{ | |
public function isValid(Request $request, string $secret): bool | |
{ | |
$signature = $request->header('X-Signature'); | |
if (! $signature) { | |
return false; | |
} | |
if (empty($secret)) { | |
throw \RuntimeException("Webhook verification key is missing"); | |
} | |
$computedSignature = hash_hmac('sha256', $request->getContent(), $secret); | |
// Use hash_equals instead of direct comparison to prevent timing attacks | |
// https://www.php.net/manual/en/function.hash-equals.php | |
return hash_equals($signature, $computedSignature); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment