Skip to content

Instantly share code, notes, and snippets.

@fideloper
Created February 6, 2024 15:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fideloper/f9fb42d719371f18b3753fe76661064a to your computer and use it in GitHub Desktop.
Save fideloper/f9fb42d719371f18b3753fe76661064a to your computer and use it in GitHub Desktop.
Verify Slack webhooks in Laravel
<?php
namespace App\Http\Controllers\Slack;
use App\Slack\Webhook;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class SlackActionController extends Controller
{
public function action(Request $request)
{
Log::info('slack action', $request->all());
if (! Webhook::verified($request)) {
return abort(400);
}
if ($request->type == 'url_verification') {
return [
'challenge' => $request->challenge,
];
}
}
}
<?php
namespace App\Slack;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class Webhook
{
/**
* Verify Slack webhook
* @link https://api.slack.com/authentication/verifying-requests-from-slack
*/
public static function verified(Request $request): bool
{
$version = explode("=", $request->header('x-slack-signature'))[0];
$requestTimestamp = $request->header('x-slack-request-timestamp');
// Check for replay attacks
$allowedTimeDelta = 60 * 5; // 5 minutes
if (now()->timestamp - $requestTimestamp > $allowedTimeDelta) {
Log::warning("Possible replay attack, Slack webhook older than ".$allowedTimeDelta." seconds");
return false;
}
// Check request signature
$rawBody = $request->getContent();
$hash_signature = hash_hmac(
'sha256',
"$version:$requestTimestamp:$rawBody",
config('services.slack.webhooks.signing_secret')
);
if (! hash_equals($request->header('x-slack-signature'), "v0=$hash_signature")){
Log::warning("Slack webhook signature did not match", [
"ours" => $hash_signature,
"theirs" => $request->header('x-slack-signature'),
]);
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment