Skip to content

Instantly share code, notes, and snippets.

@pingcheng
Last active December 5, 2023 21:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pingcheng/f7500adf1b1009df3ed341f511305b0d to your computer and use it in GitHub Desktop.
Save pingcheng/f7500adf1b1009df3ed341f511305b0d to your computer and use it in GitHub Desktop.
Laravel middleware for validating slack signing secret
<?php
namespace App\Http\Middleware;
use Exception;
use Carbon\Carbon;
use Closure;
use Illuminate\Support\Facades\Log;
class SlackRequest
{
/**
* Validate a slack request
* by the slack signing secret (not the token)
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
* @throws Exception
*/
public function handle($request, Closure $next)
{
// define the version number
$version = 'v0';
// load the secret, you also can load it from env(YOUR_OWN_SLACK_SECRET)
$secret = config('services.slack.signing_secret');
// get the payload
$body = $request->getContent();
// get the timestamp
// and compare with the local time, according to the slack official documents
// the gap should under 5 minutes
$timestamp = $request->header('X-Slack-Request-Timestamp');
if (Carbon::now()->diffInMinutes(Carbon::createFromTimestamp($timestamp)) > 5) {
throw new Exception("Invalid timstamp, too much gap");
}
// generate the string base
$sig_basestring = "{$version}:{$timestamp}:{$body}";
// generate the local sign
$hash = hash_hmac('sha256', $sig_basestring, $secret);
$local_signature = "{$version}={$hash}";
// get the remote sign
$remote_signature = $request->header('X-Slack-Signature');
// check two signs, if not match, throw an error
if ($remote_signature !== $local_signature) {
throw new Exception("Invalid signature");
}
return $next($request);
}
}
@nateSchroader
Copy link

This is awesome, thank you :)

@newvladimirov
Copy link

Thanks!

@gorkie
Copy link

gorkie commented Mar 20, 2022

Thank you 🙏

@sdapkus
Copy link

sdapkus commented Jan 12, 2023

Thanks, supper useful!

@malles
Copy link

malles commented Sep 1, 2023

Great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment