Webhook signature verification

5966
0

When receiving webhooks from external services, signature verification ensures the payload comes from the claimed sender and hasn't been tampered with. Services like Stripe and GitHub include an HMAC signature in headers computed from the request body and a shared secret. I recompute the HMAC on the received body using the same secret and compare it to the provided signature using constant-time comparison to prevent timing attacks. The raw request body must be used for signature verification, not the parsed version, which is why I sometimes need to read request.body.read before Rails parses it. Failed verification should return 401 immediately without processing the payload to avoid acting on forged requests.