Verifing Mux webhook signatures
Transcript was automatically generated and may be inaccurate.
-
–
We're now correctly handling and acting on webhooks sent to us by Mux, but we -
–
have a -
–
problem. As mentioned in the last video, all the webhook is, is a POST request -
–
being sent -
–
from another server to our application. This means that any one could -
–
theoretically send -
–
a webhook to your application and the application would just process it like it's -
–
been coded -
–
to. To combat this, Mux will send a signature along with every webhook event. -
–
We can try -
–
and recalculate this signature in our application using a secret key that only -
–
we and Mux both -
–
know, and if the signatures match, then we can be confident that the -
–
webhook event -
–
we're dealing with did in fact originate from Mux. A bad actor trying to send a -
–
fake -
–
webhook event won't be able to generate the correct signature to send with -
–
their fake -
–
webhook event, so we can safely disregard those requests. -
–
Again, Mux documentation is really good when it comes to this. If we go to the -
–
examples -
–
section, there's an example just for Laravel. So let's create some middleware -
–
to verify -
–
Mux webhook signatures. Create a new middleware class called "VerifyMuxSignature". -
–
Copy this -
–
example method from the docs. And then in our new middleware class, paste that. -
–
Whilst it does what we want from the most part, we are going to tweak it -
–
slightly. First, -
–
we need to update this config line. We're going to change the value to -
–
"services.mux.webhook.secret". -
–
We also need to import this class. We go our services/config.php file. We then -
–
need to add -
–
that configuration key. And we'll reference a MUX_WEBHOOK_SECRET -
–
environment variable. And we need to get this from our Mux dashboard. -
–
If we go to the Mux dashboard and into the "Webhook" settings, click "Show signing -
–
secret". -
–
And we need to grab this value. Paste that as a value of "MUX_WEBHOOK_SECRET". We -
–
can call -
–
this verifySignature as the very first line in our middleware. If it returns -
–
false, we -
–
want to actually abort the request. We can abort with a 403 Forbidden status. -
–
So if the -
–
signature doesn't match, the request won't be processed. Open up the Mux -
–
webhook controller -
–
class. We'll need to define a constructor. Inside the constructor, we'll call -
–
our verify -
–
Mux signature middleware that we've just created. But we'll only include the -
–
middleware if our -
–
webhook secret is actually being set. And our webhook handler has now been -
–
secured. -
–
it'll only respond to webhook events that actually originate from Mux.