Created
July 17, 2020 18:30
-
-
Save dinvlad/cb2c3e8c8cd7905b832f38db92308c64 to your computer and use it in GitHub Desktop.
Validate interactive request from Slack
This file contains 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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It turns out this implementation is not needed anymore, as
slackclient
now has methodsvalidate_slack_signature()
andis_valid_request()
, see e.g. here https://slack.dev/python-slackclient/basic_usage.html#opening-a-modal