twilio / twilio-php

A PHP library for communicating with the Twilio REST API and generating TwiML.
MIT License
1.57k stars 562 forks source link

Cant validate the incoming Twilio requests using laravel middleware #750

Closed abr4xas closed 1 year ago

abr4xas commented 2 years ago

Issue Summary

I'm trying to create a small endpoint to send SMS and validate the incoming request from twilio using this: https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-lumen-app-by-validating-incoming-twilio-requests and isn't working.

Steps to Reproduce

  1. Create a laravel middleware
  2. Create a new route to log all the sms status changes and append the middleware to that route
  3. Check the logs.

Code Snippet

<?php

namespace App\Http\Middleware\Webhook;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Twilio\Security\RequestValidator;

class VerifyTwilioRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  Request  $request
     * @param  Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next): mixed
    {
        $twilioToken = config('twilio.token');

        if (empty($twilioToken)) {
            throw new AccessDeniedHttpException('twilio token not found');
        }

        $requestValidator = new RequestValidator($twilioToken);

        $requestData = $request->toArray();

        // Switch to the body content if this is a JSON request.
        if (Arr::exists($requestData, 'bodySHA256')) {
            $requestData = $request->getContent();
        }

        $isValid = $requestValidator->validate(
            $request->header('X-Twilio-Signature'),
            $request->fullUrl(),
            $requestData
        );

        if (!$isValid) {
            throw new BadRequestHttpException('twilio payload is invalid');
        }

        return $next($request);
    }
}

Exception/Log

twilio payload is invalid

Technical details:

mattcole19 commented 2 years ago

Thank you for bringing this issue to our attention. This page goes into more detail on how our request validation works. Per below, can you try disabling the TrimStrings middleware and see if that helps?

"Some frameworks may trim whitespace from POST body fields. A notable example is Laravel, which has the TrimStrings middleware enabled by default. You must disable these behaviors to successfully match signatures generated from fields that have leading or trailing whitespace."

Please let me know if you have any more questions!

childish-sambino commented 1 year ago

Closing due to inactivity. Please re-open this issue or open a new GitHub issue if you still need help.