Skip to content

Commit fb9139b

Browse files
committed
Add Slack request verification
1 parent 1491bab commit fb9139b

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

solution/main.py

+28-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import hmac
2+
import hashlib
3+
14
from pprint import pprint
25

36
import requests
@@ -6,7 +9,7 @@
69

710
from dotenv import dotenv_values
811

9-
from fastapi import Body, FastAPI, Request, Response
12+
from fastapi import Body, FastAPI, Request, Response, status
1013

1114
config = dotenv_values(".env")
1215

@@ -16,13 +19,37 @@
1619
# This token can be obtained from the `OAuth Tokens for Your Workspace` section
1720
# In `OAuth & Permissions` in the bot settings
1821
BOT_TOKEN = config["BOT_TOKEN"]
22+
SIGNING_SECRET = config["SIGNING_SECRET"]
23+
24+
25+
def slack_validate_request(timestamp, body, slack_signature):
26+
sig_basestring = 'v0:' + timestamp + ':' + body
27+
28+
signature = 'v0=' + hmac.new(
29+
SIGNING_SECRET.encode(),
30+
sig_basestring.encode(),
31+
hashlib.sha256
32+
).hexdigest()
33+
34+
return signature == slack_signature
1935

2036

2137
@app.post("/echo")
2238
async def echo(request: Request, response: Response, data=Body(...)):
2339
raw_body = await request.body()
2440
body = raw_body.decode("utf-8")
2541

42+
# We are following the guide from here:
43+
# https://api.slack.com/authentication/verifying-requests-from-slack
44+
slack_timestamp = request.headers['x-slack-request-timestamp']
45+
slack_signature = request.headers['x-slack-signature']
46+
47+
is_valid = slack_validate_request(slack_timestamp, body, slack_signature)
48+
49+
if not is_valid:
50+
response.status_code = status.HTTP_403_FORBIDDEN
51+
return
52+
2653
# We need to add the `channels:read` scope
2754
# From the `OAuth & Permissions` section in the bot settings
2855
# This will give us `data.event.channel`, which is the channe id,

0 commit comments

Comments
 (0)