Last active
December 5, 2023 21:11
-
-
Save pingcheng/f7500adf1b1009df3ed341f511305b0d to your computer and use it in GitHub Desktop.
Laravel middleware for validating slack signing secret
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\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); | |
} | |
} |
Thanks!
Thank you 🙏
Thanks, supper useful!
Great!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is awesome, thank you :)