Created
May 6, 2020 21:55
-
-
Save nasrulhazim/7adcb6f09759adeae91153b5c481db84 to your computer and use it in GitHub Desktop.
GitHub Signature Validator
This file contains 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\WebhookClient\SignatureValidator; | |
use Illuminate\Http\Request; | |
use Illuminate\Validation\UnauthorizedException; | |
use Spatie\WebhookClient\SignatureValidator\SignatureValidator; | |
use Spatie\WebhookClient\WebhookConfig; | |
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; | |
class GitHubSignatureValidator implements SignatureValidator | |
{ | |
public function isValid(Request $request, WebhookConfig $config): bool | |
{ | |
if (! isProduction()) { | |
return true; | |
} | |
$signature = $request->header(config('webhooks.github.signature_header_name')); | |
$secret = $config->signingSecret; | |
if (is_null($signature)) { | |
throw new BadRequestHttpException('GitHub Webhook Header Not Set'); | |
} | |
$signature_parts = explode('=', $signature); | |
if (2 != count($signature_parts)) { | |
throw new BadRequestHttpException('Invalid GitHub Webhook Format.'); | |
} | |
$known_signature = hash_hmac('sha1', $request->getContent(), $secret); | |
if (! hash_equals($known_signature, $signature_parts[1])) { | |
throw new UnauthorizedException('Could not verify request signature ' . $signature_parts[1]); | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment