Skip to content

Instantly share code, notes, and snippets.

@rheinardkorf
Last active August 4, 2018 06:46
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 rheinardkorf/61b97d53584fc2d5438f3819ac519dc8 to your computer and use it in GitHub Desktop.
Save rheinardkorf/61b97d53584fc2d5438f3819ac519dc8 to your computer and use it in GitHub Desktop.
Verifying Slack Requests
<?php
/**
* Validate Slack notification signature.
*
* @see https://api.slack.com/docs/verifying-requests-from-slack
*
* @param array $headers POST headers.
* @param string $response_body JSON string of body.
* @param string $signing_secret Slack secret.
*
* @return bool
*/
public function validate_signature( $headers, $response_body, $signing_secret ) {
// If signature fields aren't present then bail.
if ( ! array_key_exists( 'x_slack_request_timestamp', $headers ) || ! array_key_exists( 'x_slack_signature', $headers ) ) {
return false;
}
$data = sprintf( 'v0:%s:%s', $headers['x_slack_request_timestamp'][0], $response_body );
$signed_payload = 'v0=' . hash_hmac( 'sha256', $data, $signing_secret );
// Compute signature with SHA1 function and compare to header value.
if ( $headers['x_slack_signature'][0] !== $signed_payload ) {
// Signatures DON'T match
return false;
}
// Compare the current time to the received timestamp.
if ( strtotime( '-30 minutes' ) >= $headers['x_slack_request_timestamp'][0] ) {
// Signatures match, but older than 30 minutes.
return false;
}
// Signatures match, and timestamp is valid.
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment