Skip to content

Instantly share code, notes, and snippets.

@dinvlad
Created July 17, 2020 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dinvlad/cb2c3e8c8cd7905b832f38db92308c64 to your computer and use it in GitHub Desktop.
Save dinvlad/cb2c3e8c8cd7905b832f38db92308c64 to your computer and use it in GitHub Desktop.
Validate interactive request from Slack
import hashlib
import hmac
import os
from time import time
from flask import Request, abort
SLACK_SIGNING_SECRET = os.environ['SLACK_SIGNING_SECRET']
def validate_slack_request(request: Request):
"""
Validates that request came from Slack.
Ref: https://api.slack.com/authentication/verifying-requests-from-slack
"""
timestamp = request.headers['X-Slack-Request-Timestamp']
if abs(time() - int(timestamp)) > 60 * 5:
# The request timestamp is more than five minutes from local time.
# It could be a replay attack, so let's ignore it.
abort(401)
sig_basestring = 'v0:' + timestamp + ':' + request.get_data().decode('utf-8')
req_signature = 'v0=' + hmac.new(
SLACK_SIGNING_SECRET.encode('utf-8'),
sig_basestring.encode('utf-8'),
hashlib.sha256,
).hexdigest()
slack_signature = request.headers['X-Slack-Signature']
if len(req_signature) != len(slack_signature) or \
not hmac.compare_digest(req_signature, slack_signature):
abort(401)
@dinvlad
Copy link
Author

dinvlad commented Jul 24, 2020

It turns out this implementation is not needed anymore, as slackclient now has methods validate_slack_signature() and is_valid_request(), see e.g. here https://slack.dev/python-slackclient/basic_usage.html#opening-a-modal

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