I am trying to implement a python function to validate the post request signature. However, the expected signature (using the compute_signature) does not match what is provided by the Twilio request – so the validate function always returns False. I’ve tried a number of different permutations to get the form params, but cannot get the expected signature to match.
The approach to get the url and params are consistent with the Twilio tutorial: linked. The AUTH_TOKEN matches that in the Twilio console (account info). Has anyone experienced this problem and determined a solution?
from fastapi.security.api_key import APIKeyHeader
from fastapi import Security, HTTPException, Request
from twilio.request_validator import RequestValidator
signature_header = APIKeyHeader(name="X-Twilio-Signature", auto_error=False)
async def validate_signature(request: Request, signature: str = Security(signature_header)):
if not signature:
raise HTTPException(403, "No signature provided")
validator = RequestValidator(settings.AUTH_TOKEN)
url = str(request.url)
params = dict(await request.form())
print(f"Twilio signature: {signature}")
print(f"Expected signature: {validator.compute_signature(url, params)}")
if not validator.validate(url, params, signature):
raise HTTPException(403, "Signature verification failed")
return True
I’ve implemented the code from the Twilio tutorial exactly – and this does not work either. I’ve also reviewed the Twilio request_validator.py implementation: linked, which appears to be fine.
2