twiliotwilio-apitwilio-functions

Get access to headers and raw request body in Twilio serverless function


I have a Twilio serverless function that handles request from another system that provides authentication via JWT. In order to decode the request encoded with JWT I need to get the raw request body. According to the Twilio Functions docs (https://www.twilio.com/docs/runtime/functions/invocation) state:

The event object contains the request parameters passing into your Function. Both POST and GET parameters will be collapsed into the same object. For POST requests, you can pass either form encoded parameters or JSON documents; both will be collapsed into the event object. Currently, it is not possible to access request headers in the function execution context.

This sounds like getting the raw request body isn't possible. Is there some way to achieve this? Request bodies won't ever be valid JSON because they are encoded and will need to be decoded before the business logic in the handler can be executed.


Another endpoint in this same Twilio service needs to authenticate requests from Twilio as it is setup as a webhook for incoming SMS for our phone numbers. According to the docs (https://www.twilio.com/docs/usage/webhooks/webhooks-security) the signature is sent in the request as a header. According to the excerpt from docs above aren't accessible from the Twilio Functions handler. Is this also not possible in Twilio Functions?


Solution

  • Twilio developer evangelist here.

    I can answer your second question, but I may need some more details for the first one.

    Twilio Functions have visibility settings. You can set them to public, protected or private. Public means they are accessible to anyone with the URL, private means they do not have a URL and can only be accessed from within the Functions service.

    Protected functions will validate the X-Twilio-Signature header and only respond to requests that have a valid signature. So you do not need access to the headers (though that feature is on its way), you can just set your function to be protected.

    enter image description here


    Can you give me any more information about the incoming JWT request? Are you saying that the entire request body is just a JWT (so a base64url encoded string)? What Content-Type header is sent with the request?