Created
July 5, 2020 20:50
-
-
Save mdeggies/2d60a30d1c3e216c1efbdba4f69b8912 to your computer and use it in GitHub Desktop.
Slack validation in Python3
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
def validate_request_source(request): | |
"""Validate that the incoming request is from our own slack instance in Python3 | |
Returns True if the request is valid, False otherwise""" | |
try: | |
if 'X-Slack-Request-Timestamp' in request.headers and 'X-Slack-Signature' in request.headers: | |
timestamp = request.headers['X-Slack-Request-Timestamp'] | |
expected_signature = request.headers['X-Slack-Signature'] | |
# Reject replay attacks | |
if (int(timestamp) + (60 * 5)) < int(time()): | |
return False | |
data = request.get_data().decode("utf-8") | |
basestring = f"v0:{timestamp}:{data}".encode('utf-8') | |
slack_signing_secret = bytes(os.environ['slack_signing_secret'], 'utf-8') | |
signature = 'v0=' + new(slack_signing_secret, basestring, sha256).hexdigest() | |
# Compare signatures | |
if compare_digest(signature, expected_signature): | |
return True | |
return False | |
except Exception as e: | |
print('Failed to validate request source: {}.'.format(e)) | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment