Purchase access to watch this video.

Unlock course for £159

Already purchased access? Login

Verifing Mux webhook signatures

  1. We're now correctly handling and acting on webhooks sent to us by Mux, but we
  2. have a
  3. problem. As mentioned in the last video, all the webhook is, is a POST request
  4. being sent
  5. from another server to our application. This means that any one could
  6. theoretically send
  7. a webhook to your application and the application would just process it like it's
  8. been coded
  9. to. To combat this, Mux will send a signature along with every webhook event.
  10. We can try
  11. and recalculate this signature in our application using a secret key that only
  12. we and Mux both
  13. know, and if the signatures match, then we can be confident that the
  14. webhook event
  15. we're dealing with did in fact originate from Mux. A bad actor trying to send a
  16. fake
  17. webhook event won't be able to generate the correct signature to send with
  18. their fake
  19. webhook event, so we can safely disregard those requests.
  20. Again, Mux documentation is really good when it comes to this. If we go to the
  21. examples
  22. section, there's an example just for Laravel. So let's create some middleware
  23. to verify
  24. Mux webhook signatures. Create a new middleware class called "VerifyMuxSignature".
  25. Copy this
  26. example method from the docs. And then in our new middleware class, paste that.
  27. Whilst it does what we want from the most part, we are going to tweak it
  28. slightly. First,
  29. we need to update this config line. We're going to change the value to
  30. "services.mux.webhook.secret".
  31. We also need to import this class. We go our services/config.php file. We then
  32. need to add
  33. that configuration key. And we'll reference a MUX_WEBHOOK_SECRET
  34. environment variable. And we need to get this from our Mux dashboard.
  35. If we go to the Mux dashboard and into the "Webhook" settings, click "Show signing
  36. secret".
  37. And we need to grab this value. Paste that as a value of "MUX_WEBHOOK_SECRET". We
  38. can call
  39. this verifySignature as the very first line in our middleware. If it returns
  40. false, we
  41. want to actually abort the request. We can abort with a 403 Forbidden status.
  42. So if the
  43. signature doesn't match, the request won't be processed. Open up the Mux
  44. webhook controller
  45. class. We'll need to define a constructor. Inside the constructor, we'll call
  46. our verify
  47. Mux signature middleware that we've just created. But we'll only include the
  48. middleware if our
  49. webhook secret is actually being set. And our webhook handler has now been
  50. secured.
  51. it'll only respond to webhook events that actually originate from Mux.
Connect GitHub