Last active
August 4, 2023 13:20
-
-
Save dorukgezici/cd90e6497881b63095a7efc8e1aa4e8f to your computer and use it in GitHub Desktop.
ASGI middleware for Slack signature verification on FastAPI - Starlette
This file contains hidden or 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 os | |
from asyncer import asyncify | |
from fastapi import HTTPException, Request | |
from slack_sdk.signature import SignatureVerifier | |
from starlette.status import HTTP_403_FORBIDDEN | |
from starlette.types import ASGIApp, Receive, Scope, Send | |
signature_verifier = SignatureVerifier(signing_secret=os.environ["SLACK_SIGNING_SECRET"] | |
class SignatureVerifierMiddleware: | |
def __init__(self, app: ASGIApp): | |
self.app = app | |
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: | |
if scope["type"] != "http": | |
return await self.app(scope, receive, send) | |
async def verify_signature(): | |
message = await receive() | |
assert message["type"] == "http.request" | |
request = Request(scope) | |
# Slack signature verification | |
if not await asyncify(signature_verifier.is_valid)( | |
body=message.get("body", b""), | |
timestamp=request.headers.get("X-Slack-Request-Timestamp", ""), | |
signature=request.headers.get("X-Slack-Signature", ""), | |
): | |
raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="signature denied") | |
return message | |
await self.app(scope, verify_signature, send) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment